How to work with Ajax (overview)
Asynchronous JavaScript and XML (aka Ajax) is a great technique for refreshing your web page without forcing a full reload of the page. It allows developers to ask for only pertinent parts of the page, resulting in a much more responsive web site. But working with Ajax can be challenging for those just getting started.
The process
An Ajax call is processed like this:
S B
E <---- Standard HTML Request ---- R
R ---- HTML Response -------------> O
V W
E <---- Ajax Request ------------- S
R ---- Ajax Response -------------> E
R
First, the browser requests a web page as usual. It gets a response and renders the page to the screen. At this stage, some JavaScript is involved to set up when an Ajax request is made. This could be a timer to simply keep part of the page up to date, or it could be in response to a user action - typing, clicking, etc.
At some point an Ajax request is sent to the server. This is done WITHOUT reloading the web page. The "XMLHTTPRequest" object is used to make this request. A response is then sent back. The server at this point doesn't know (or care) if it is dealing with a browser or not - it got a request and has responded. The browser knows when the response has arrived (via the XMLHTTPRequest object), and then does further processing on that response. It could be as simple as changing the innerHTML of a DIV to the HTML code returned, or it could be building complex tables based on the resulting XML.
(disclaimer - some coding languages DO make a distinction between a standard HTML request and an XHR (aka Ajax) request. That details is for a different web site though...).
The important point here is to note that there are two parts to an Ajax request - the server side, and the browser side.
The Server Side
We need to create a file that can be requested from the browser. This could be a regular HTML or text file, or it could be server side code (a la PHP, Perl, .NET, etc.). Regardless it must return something to our browser.
The JavaScript support forums/IRC Channels, etc. are full of requests for help that eventually boil down to the server side resource is resulting in an error. If you get an error from the server side resource(s), then the rest of the process will be suspect as well.
A common troubleshooting technique when dealing with Ajax is to load the server side resource directly. For instance if we are calling "thelist.txt", then we should be able to punch in the URL for that file. If that doesn't result in what we have expected then our URL is wrong, or the file has a problem. These would need to be resolved. If we are asking for "my_data.php", then we should punch in the URL for that file and see what we get back. If PHP or database errors are being reported, then these issues need to be resolved. If you are using a POST to pass data to your server, the request you need to make may be more troublesome. Using Firebug will help spot errors and see just what is being passed to your server.
We STRONGLY recommend using FireFox and Firebug when working with Ajax. Firebug reveals a great deal of detail about your Ajax requests - including the HTTP request and response, the parameters passed to the server regardless of the request method (GET/POST), and the results returned by the server. The results is much the same as asking for the page directly in the browser.
When you know your server side processing is doing what it should in a reliable manner, you are ready to look at the browser side of the equation.
The broswer side
In your browser, you need to make an Ajax request. jQuery makes this very easy. But the question is what you are doing with the response you will get. If you are asking for XML data, you will probably be processing that data to build parts of your interface. Or perhaps you are simply deciding what further action is needed. If you are getting raw HTML, you will likely be placing that value into your page somewhere. This part is highly dependent on your own needs. But we can help you in getting to that point.
We'll focus on using the $.ajax() method here. It will highlight all the important parts of the Ajax process we need to worry about.
- Make sure you are asking for the right server side resource/page. Asking for the wrong URL is a surefire way to get unexpected results.
- Make sure you are doing the right type of request - GET or POST. If you are passing data to the server, you would normally want to use a POST unless the data was non-sensitive, small in quantity, and otherwise insignificant in terms of who could visually see that data. Treat this type much the same way you would a form's "method" property.
- Make sure you are passing the correct data. The $.ajax() method uses the same technique for passing GET and POST data. This is the standard "param=value¶m=value¶m=value" method you are likely familiar with from working with URLs. (actually, this stems for the HTTP standards, not just jQuery.)
- Make sure you are asking for the right type of response. This is where jQuery differs some from traditional JavaScript. The traditional method is that you deal with either the .responseText or .responseXML properties of the XMLHTTPRequest object. jQuery helps hide the details here and allows us to specify a "dataType". jQuery will then do some pre-proccessing of the response to put the data into the expected format. For XML, you would get an XML object in response. For "json", you would get a JavaScript object in response. For "html", you would get a DOM fragment you can work with. For "text", you would get a string. But asking for "json" and getting an XML response would be a source of errors.
- Check for errors. Make sure you are doing proper error checking. There are times where the Ajax request may complete successfully, but the response data has a problem with it.
- Know that under the hood, jQuery is using an XMLHTTPRequest object. In the error handler, this object is one of the arguments. So you can inspect the .responseText directly if needed.
- Do something with the results. Sometimes people will make an Ajax request and then not understand why things are working. Making the request is only the first step. You must do something with the results. It could be as simple as replacing the contents of a DIV, or perhaps you got an array of objects back in JSON format and you need to build a table from that data. If you don't do something with the results, you won't see any errors (assuming everything else worked properly), but you won't see any resulting actions either.
While the above comments are hidden in some degree or other with the other Ajax methods in jQuery (.load(), .get(), etc.) they are all still there. Understanding Ajax on it's own is VERY useful to doing it with jQuery.
To highlight some of the above, here is some sample code:
$.ajax({
url : "employee_sales_json.php",
type : "POST",
data : "employee=" + $("#employee_id").attr("id"),
dataType : "json",
error : function (xhr, desc, exception) { alert(xhr.responseText); },
success : function (data) {
//assuming an Array of objects was retreived
var output = "<ul>";
for (var x=0; x < data.length; x++) {
var sale = data[x];
output += "<li>";
output += "Type: " + sale.type + ", ";
output += "QTY : " + sale.qty + ", ";
output += "Total: " + sale.total;
output += "</li>";
}
output += "</ul>";
$("#employee_sales").html(output);
}
});
You can see here that we have "posted" the employee ID to our "employee_sales_json.php" file. We have indicated we are expecting our results to be a JSON object. We are handling any unexpected errors by doing an alert on xhr.responseText. The first argument passed to the error function is the raw XMLHTTPRequest object. We could have easily put this into an "error div" and any HTML in the error message would be rendered. Finally we handle the data resulting from our request. The data is passed as an argument to the success function. The name of the parameter is irrellevant - some use "json", some use "data", some use "html". Call it something meaningful to you.
In this sample we are processing a JSON response and building up an output. The nice thing about using JSON like this is that this exact same server resource can be used in a different manner. Perhaps we have a select list that needs to show the recent "sale types" for the employee. This same code could then be utilized to populate that list.
Further details
The heart of any Ajax request is the XMLHTTPRequest (XHR) object. Requests are (normally) done in an asynchronous manner. This means we need some way to track what is happening to the object. For this reason the XHR object has two properties - "readyState", and "status". The status is simple - it exposes the HTTP status code. If everything went ok, the status would be "200". If the requested page couldn't be found, the status would be "404". The readyState isn't quite as straightforward though.
The readyState has 4 states we are concerned with:
0 = uninitialized
1 = loading
2 = loaded
3 = interactive
4 = complete
State zero indicates we have only instantiated the object, but have not begun using it.
State 1 indicates a request has been made.
State 2 indicates a response has been received
State 3 indicates that the browser and server are communicating.
State 4 indicates that we have received a response and the XHR object has completed it's processing.
Usually we are only concerned with state # 4. A common snippet of code makes use of the readyState AND the status.
. . .
if (xhr.readyState == 4 && xhr.status == 200) {
//we can proceed with processing.
}
Where jQuery is concerned, the "success" function is not fired until the readyState is at "4", and we have a "200" status. Any other status would indicate an error (well, not quite, but close enough for now). Any other readyState indicates the response has not been received yet.
While this level of detail is not really needed when using jQuery, it is still good to know in general. It helps to figure out some glitches, and gives a peek into what jQuery is doing for us. (Or we can just go look at the source code....)
- Printer-friendly version
- Login or register to post comments
