jQuery + AJAX + PHP: Part 2: Understanding AJAX

jQuery + AJAX + PHP


Understanding AJAX

As mentioned in the first part, AJAX originally stood for “Asynchronous JavaScript And XML.”

The initial concept was developed first at Microsoft as part of a system to access to parse XML documents in early 1999. By the next year, Mozilla then created a generic JavaScript object to access its own internal implementation called XMLHttpRequest. This slowly became the standard as more companies and products adopted the name and usage after seeing both Microsoft and Mozilla working on the idea. By the end of 2005, many browsers had adopted it.

AJAX was originally designed for XML. As part of the name, the XMLHttpRequest object was developed for use with servers that would return XML results. However, this purpose was quickly expanded through its use with text as a way to request and get responses from servers after a website had initially loaded its contents. By the late 2000s, AJAX, as it soon became called, was used in popular web applications like Google’s Gmail and many others.

Using AJAX

var request = new XMLHttpRequest();

request.onreadystatechange = function () {
    var DONE = this.DONE || 4;
    if (this.readyState === DONE) {
        // Data loaded. Do something!
    }
};
request.open('GET', 'somepage.xml', true);
request.setRequestHeader('X-Requested-With', 'XMLHttpRequest');                                               
request.send(null);

In its most basic form, a new XMLHttpRequest() object is created. If wanted, a onreadystatechange callback function can be set. (There are five ready-states depending where in the process the current call is at any one point.)

The open() function initializes the call. If any headers are needed, the setRequestHeader() function can be used.

Finally, the send() function actually sends the request after it has been constructed.

What does this have to do with jQuery?

Instead of needing to write out a callback function and any needed headers, jQuery simplifies all of these operations.

$.ajax({
        method: "GET",
        url: "response.php",
        data: { name: "Dan", example: "Yup" }
      })
      .done(function( message ) {
        $("#log").text(message);
      })
      .fail(function( message ) {
        $("#log").text(message);
      });

Its done() and fail() functions act as part of the onreadystatechange callback and are called depending on the final state. The ability to quick encode data as part of the url and data also allow for quickly writing AJAX calls without needing to create a new object and configuring it each time.