1. Technology
Send to a Friend via Email

Learn AJAX

This series of tutorials will introduce you to AJAX by taking you step by step through the code of a simple example.

Creating an XMLHttpRequest Object
The XMLHttpRequest object is what you use to give Javascript the ability to request information from the server.

Opening a Request
Once we have our request object defined the next step is to use it to connect to the server side processing that will retrieve the required information for us.

Response Event Handler
With our AJAX object created and opened, the next step is to define the enent handler that will process the response when it comes.

Send the Request
The final step before control passes to the server is to send the request.

Passing Parameters
There are several different ways of passing information to the server to tell it what the request is for. Here we look at how to modify our request to make different requests.

Success or Failure
With the sending of the request taken care of we now return to the response event handler and add the code needed to test if the request worked.

Response Type
Having determined that our request was successful we now look at how we can test what type of response we got back - XML or plain text.

responseText and responseXML
Depending on the content type the response is returned in one of two different properties.

Setting Response Type
The server side processing determines the content type of the response.

Javascript Object Notation
The obvious format to use for the response is JSON (since it is both more compact than XML and its relationship to Javascript makes it easier to use).

Parsing XML
The responseText field is always returned with a copy of the response so why is there also a responseXML field that gets returned as well but only if the response is XML? Well the responseXML field has already parsed the XML that is in the response for us making it much easier to access the information from Javascript.

Aborting AJAX
Since we are using an asynchronous link to the server our visitor could always change their mind about what they want before it finishes updating. By aborting the prior request we avoid problems.

Multiple Requests
When you want to be able to submit multiple requests to the server without aborting prior requests you need to create multiple request objects.

Caching of Requests
Some browsers will just return the cached value when you make a second request to the server that looks the same as the first. There are two ways to resolve this to force the browser to pass all of your Ajax requests to the server.

Ajax and Security
Securing an Ajax application is no different from securing any other server side processing because any attacks will be directed at the server end of the code without the attacker using Ajax in their attack.

©2014 About.com. All rights reserved.