Submitting a form via AJAX

Ok so here is a very simple yet descriptive example how web-forms can be submitted using AJAX. This is an advanced tutorial, so although I’ll try to explain everything, I am assuming that the reader has a basic understanding of php and javascript.

AJAX is Asynchronous JavaScript And XML. Its a client side method to communicate data with a server. Asynchronous means that this communication can take place without interfering with other client side processes. (As we’ll see later, the asynchronous part is optional). Javascript is the main framework where AJAX works and XML is a format in which data might be communicated. Although this is not necessary. Data might be communicated in text, JSON, etc formats also.

Lets jump right in and look at this live demo.

Ok, lets look at the code now. The HTML structure is something like this:
http://pastebin.com/embed_iframe.php?i=tQEjujan

Its not difficult to understand, really. There are two main divs inside the body tag. form and list. Pretty self descriptive. If you look at the code, I haven’t added any target to the form. (the action attribute). In fact I have added a return false value to the onsubmit event handler. This means, that the form won’t be submitted the traditional way when a user clicks the submit button. Rather it will use the event handler onclick of the submit button, which calls a javascript function submitUser().

So you might ask, why I didn’t do it the conventional way. For one reason, on form submission, even if the action attribute is empty, the page will refresh. This defeats our whole purpose of using AJAX. Also, there might be other ways to do the same, but I prefer this one as I find it easier. 🙂

Moving on, as you see in the <head> section, I have included a js file and have initiated a javascript function called initiate(), when the page is loaded. Both the functions initiate() and submitUser() are inside the js file user.js. Lets have a look at the code.

http://pastebin.com/embed_iframe.php?i=i9zH7VXU

The code is longer than required, but I have tried to keep it simple for understanding.

This is what happens inside the submitUser() function:
1. Read the value of the user name from the form.
2. Create an xmlhttp object to communicate with the php script.
2. Send the value of the user name to the php script submitUser.php via the xmlhttp object
3. When the value is stored in the database, refresh the list by calling the function initate()

What the function initiate() does is:
1. Create an xmlhttp object.
2. Call a php file which  reads out database and fetches the names in the table.
3. When the data is ready from the php file, it is displayed inside the list div.

Now lets break it down. Starting with submitUser() function:

The first few lines of code:

element.disabled = true;
element.value = "saving";
var user = document.getElementById("userName").value;

To make it graphically more human, when the user clicks the submit button, we have disabled the button and changed it’s value to “saving”. And when the form is submitted, reset it. This make more sense. “element” is a parameter to the submitUser() function. If you look at the index.html file, in the form. I am passing this as a parameter to the funtion. The keyword this here points to the tag inside which it is used: the submit button. Thus, the above lines of code, disable the button and change it’s value to saving. Ok lets move on.

var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}

This code creates an xmlhttp object. An xmlhttp object is an essential component of AJAX. It handles all the communicating that is done via AJAX. Due to browser incompatibility, we define it twice. Once for, the latest browsers and the other for older versions of internet explorer. Cool! Lets now look at the last two lines first:

xmlhttp.open("GET","scripts/submitUser.php?user="+user,true);
xmlhttp.send();

These two codes perform the function of sending the variable “user” to the PHP script via the GET method. In .open() funtion, the first parameter is the method (in our case GET), the second parameter is the url of the php script and third is true or false based on whether we want the communication to take place synchronously or asynchronously. The difference is that in the earlier case, no other processes are put on hold while communicating with the php script. And now the rest of the code:

xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
if(xmlhttp.responseText!="")
alert(xmlhttp.responseText);
document.getElementById("userName").value = "";
element.disabled = false;
element.value = "alright!"
initiate();
}
}

The onreadystatechange handler is used to run some code, when the php side processing is done. The “if” statement checks if no error occured during all this was happening. When everything turns out OK, we do a couple of things:
1. If some response came from the php script, we alert it to the user.
2. Reset the form. Make the field empty, enable the button and reset the text displayed inside it.
3. Call the initiate() function which updates the list.

Pheww. Too much code ,heh!! Relax, most of it is done. Now lets have a look at the code of the php script which was used in the submitUser function
http://pastebin.com/embed_iframe.php?i=4DLdTLWB

Hmm, small enough. The first line, initializes the connection with database. The second line, stores the GET variable user into a php variable $user. The next few lines, store this into a table and if error happens during this it will echo it. Now lets go back to the list of jobs performed by the code inside the onreadystatechanged event handler, point 1. If some response comes in from the php file, it will alert the user. Thus, if some error happens inside the php code, it will be alerted to the user. This is a safety measure we take, so that the user is notified if anything goes wrong in the backend.

Now, moving on to the code of the initiate() funtion:
This one is simpler, the first line of code document.getElementById("list").innerHTML = '<img src="loader.gif" />'; is again a step to make the code more human. It will show a loading image in the “list” div until the list is fetched from the php script. Sometimes what happens is, due to slow connection, it takes a lot of time to fetch data from the database. In such a case the list, div is empty and the user has no way of knowing the status at the backend. The loading gif makes it easy for us users.
The rest of the code is something similar to what we saw in the submitUser function: Creating an xmlhttp object and communicating with the php script: fetchUsers.php. There is one difference though, we are not sending any parameters to the script. And we are displaying whatever response is coming, into the “list” div.

Now for the php code of fetchUsers
http://pastebin.com/embed_iframe.php?i=uRrnZ8Hn
Nice! The php code is crystal clear:
1. Connect with the database.
2. Read the table and hence all the names.
3. If table is empty, then send “No users yet” as response.
4. Else, send as response a list of names fetched from the database.

THATS IT. ALL DONE.

Now if you guys got stuck with the php code, here‘s an excellent tutorial on communicating with a database via php. Also on the “methods” to send data, here’s some reference.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s