New Posts

Friday, May 20, 2011

Ajax 101

Asycnronous Javascript And XML, the mysterious entity known as AJAX.

What is it? What does it do? In simple terms its a method of connecting a website to a server side script without needing to submit a form, or reload a page.

For years the usual way of getting data from the server was to submit a form with values to be processed by the server which would in turn return the results of its process. This usually slowed down websites considerably, and there was no real time interaction between the user and the website.

Ajax solves this by opening a direct connection to the server, and requesting the data processing without needing to submit a form.

Ajax is composed of 3 main sections:
  • The Javascript that executes the Ajax call
  • The Ajax that calls the server side script
  • The Server side Script that takes the parameters and produces the data to be returned to the website.



The main component of AJAX is the XMLHttpRequest object. This thing does it all. It opens the connection, waits for the results, and then makes them available to JS for any further parsing or usage.

But before we can use that we need our Server Side process. This can be pretty much any script that returns data, and it can be done in pretty much any language the server can execute. PHP, ASP, Coldfusion etc...

For our example we'll be using PHP.

The Server Side Script

The Server Side Script has one important task to accomplish, and that is to produce the results we need. The script should be designed like any server side script, except we don't need full html tags as we are going to deliver this to our Javascript layer for usage in an already established page.

So basically all we want is for our script to output our data. We could include a table structure or some other markup if we require, but only if we don't plan for your JS side to do anything to data, otherwise outputting in usable formats such as comma separated strings, or a JSON object is enough.

For our example script we'll just have a process that takes a value from the POST array and echoes it out in a string.

PHP Script


<?PHP

if(isset($_POST['id'])){

echo "The ID Passed is: $_POST[id]";

}

?>





Javascript and Ajax

No we need a way of calling our server side script, and getting back the results. to do this we will require the XMLHttpRequest object from the JS window object.

We start by defining our request object:

Request Object


var requestObj=new XMLHttpRequest();




We can now use our new object to initiate the call to our server side script. However before we can do that we'll need to make a decision. do we want our call to be synchronous or asynchronous. A synchronous call means the Js stops and waits for the server to complete the processing before continuing on, this effectively makes the website hang and be unresponsive until the call is finished. Ultimately we would only use this if don;t have lots of processing to do and the response would be returned rather quickly.

Otherwise we'll want to use the asynchronous method which as it implies lets the website and all JS functions continue to run while the server process is being executed. This allows the user to keep doing things while the request is under way.

We are going to go for the asynchronous method, so we need to
setup a function to handle the data once it returns. For this we use the onreadystatechange event of our ajax object. onreadystatechange triggers every time the the readystate property changes. The readystate property simply holds the status of our request. We want it to be 4 so the Request is complete. The other values are not relevant in the context of a webpage as you can't actually do anything about them.

We also have to check the status property. The value we want is 200, which stands for "O.K." that means the call to our server side script executed correctly and data was returned. Status has many values that you can check; most are the standard HTTP status codes like the classic 500 Internal Server Error, 404 Not found error etc...

We check for both those values, and if they are 4 and 200 we can proceed to use the responseText value to get whatever our script produced as output.

Request Object and Properties


requestObj.onreadystatechange=function()
{
if (requestObj.readyState==4 && xmlhttp.status==200)
{
var results=requestObj.responseText;
document.getElementByID('myDiv').innerHTML=results;
}
}




We can then use our results to populate anything we need using regular JS calls. In the example above I simply placed everything into a div.

The next part of our Ajax interaction is to call our actual script. We'll use the open() method to define our script address, the method we want to use, and the type of call (synch vs asynch) amongst other things.

The Open method


xmlhttp.open("POST","script.php",true);




The Methods are the same ones used in a From, GET or POST. POST is the better alternative if you plan on sending a lot of data to be processed.

The address of our script is the second value we need to set. the request object is limited to reading scripts form the same domain it originates so you can;t go out and read pages from other websites to mash up into your own site.

We then need to set up our headers. Since we are basically recreating the function of a form, we set it up as such.

Headers


requestObj.setRequestHeader("Content-type","application/x-www-form-urlencoded");




And finally we need to send our parameters to our server side script.

Send Paramters


xmlhttp.send("id=" + value + "&action=list");




The parameters will appear in our POST array inside our server side script. In the case of PHP the $_POST variable.

You can set a string, or you can add values from variables or both like above by using concatenation. "value" is a variable that contains the id we wish to pass. We separate each pair with an ampersand &

With that we are done, we can setup our ajax call to be executed when a button is pressed.

Button Call


Enter ID: <input type="text" id="idbox">

<input type="button" onclick="runAjax();">




With that done, inputing an ID and pressing the bun will run our Ajax function and in turn execute our PHP script without needing to reload the page.

In our next installment we'll be looking at a slightly more complex example, by getting data from a database on the fly.

Working Example





Download the example:

Questions? Comments? Use the comment form.

No comments:

Post a Comment