Introduction to AJAX

AJAX (Asynchronous JavaScript And XML) is a set of web development techniques using many existing web technologies on the client-side to create asynchronous Web applications. With Ajax, web applications can send data to and retrieve from a server asynchronously without fully reloading the page. XMLHttpRequest (XHR) object is used to communicate with server-side scripts in in a variety of formats like JSON, XML, HTML, and even text files.

Ajax requests are triggered by JavaScript code which sends a request to a URL. The request is processed by the server and the server sends a response. JavaScript code handles the response. Since the Ajax interactions are handled asynchronously in the background, a user can continue working with the page.

AJAX is not a programming language, but a group of technologies, each flourishing in its own right, coming together in powerful new ways. It follows the following open standards:
» XHTML and CSS for presentation
» HTML/DOM (Document Object Model) selection and manipulation
» XMLHttpRequest objects for asynchronous server communication
» JavaScript for binding everything together

Implementing AJAX

To make an HTTP request to the server using JavaScript, you need an instance of XMLHttpRequest Object.
Syntax for creating an XMLHttpRequest object
[code]
variable = new XMLHttpRequest();
[/code]

For older versions of Internet Explorer (IE5 and IE6) use an ActiveX Object:
[code]
variable = new ActiveXObject(“Microsoft.XMLHTTP”);
[/code]

After receiving the response from server, you need to specify JavaScript function to handle processing of the response by setting the onreadystatechange property of the object.
[code]
xhr.onreadystatechange = functionName;
[/code]
Or you can use anonymous function as
[code]
xhr.onreadystatechange = function(){
// process the server response
};
[/code]

After defining the response handling function, you need to call the open() and send() methods of the HTTP request class, like this:
[code]
xhr.open(‘GET’, ‘processing-file.php’, true);
xhr.send(null);
[/code]

The function should check for the state of the request. If the state has the value of XMLHttpRequest as 4 (complete), you can continue processing it.

 

Putting it all together

[code]

var xhr = new XMLHttpRequest(); // Initialize the HTTP request.
xhr.open(‘get’, ‘processing-file.php’);
xhr.send();

xhr.onreadystatechange = function () {
if (xhr.readyState === 4) { // readyState 4 means the request is complete.
if (xhr.status === 200) { // status 200 means Successful return
alert(xhr.responseText);
}
else {
alert(‘Error: ‘ + xhr.status); // Display the error.
}
}
};
[/code]

You can use jQuery to make life easier with AJAX functionality. jQuery offers both a full-featured $.ajax() method, and simple convenience methods such as $.get(), $.getScript(), $.getJSON(), $.post(), and $().load().

Leave a Reply