Never miss a story!

Get weekly updates, right in your mailbox.

*We hate spam too!. You will receive only updates.
close sharing button

Send HTML Forms on Blogger Asynchronously Using AJAX

Have you ever faced challenges when designing a form on blogger to capture user input and send it to the server for processing?


Its a fairly common requirement for any blogger to use a form to send data. But most of the time when the form is submitted it opens a page where it sends the data. Today, I will show how to send form using AJAX without opening new document page. 

So what is AJAX? 

AJAX is acronym for Asynchronous JavaScript and XML. It allow us to send the data asynchronously  to the server in background and making it possible to update page, without reloading. When the form is submitted a event listener attached to the form element passes the control to a JavaScript function which then proceeds to send data asynchronously using the XMLhttpRequest Object

First, we will design a simple form.

Copy and paste above into the HTML Section of page and it should look like below

Then comes the JavaScript to send the form to the server through AJAX.
Lets design a function to send the data.

The main drawback of the AJAX method, the page where the data is sent should be on the same domain. If it is not on the same domain then it will be blocked by the browsers. You can still do a workaround on this issue which I will tell you later in the article.

AJAX is not supported by all the browsers and there is different way of implementing AJAX in different browsers. For example, Opera 8.0+, Firefox, Safari and Chrome will support the new XMLHttpRequest(); but browser like Internet Explorer requires you to use the ActiveX Object for the this purpose.

You can replace this code in above const xmlhttp = new XMLHttpRequest(); with more browser specific JavaScript code below

This is the example of Front end code. You would also require corresponding code on the server. Depending on the type of server, this can be done in PHP or Active Server Pages or any language available on the server. If its a third party API, then there will a documentation guiding you with implementing the communication between the AJAX code and the Server.

Great User Experience

When AJAX requests are sent to a domain which is not the same as where the page is stored, the requests are blocked by browser as this causes CORS Issue. Read the below article to correct the CORS issue.

Knowing AJAX can help you make simpler pages that update using the response from server. It is useful when communicating with various APIs on the internet.

No comments:

Post a Comment