What is AJAX and how does it work? [duplicate]

AJAX, or (A)synchronous (J)avascript (A)nd (X)ML (which interestingly enough tends to use JSON more these days), is a system in which Javascript uses a browser object to communicate with a remote server. The general use case of this is to be able to update a client’s interface without needing to go to another page. Before we begin though, a few words of caution.

  • Ajax is not recommended for login authentication and posting forms
  • Users can turn off Javascript, or may be restricted from running Javascript due to IT policies
  • With this in mind it is advised that you do not use AJAX as the sole solution for critical user functionality! Always have a fallback!

Note: This community wiki post uses JQuery to show the example AJAX calls. It’s recommended for newcomers as it hides the browser compatibility issues of making AJAX calls. Please check the JQuery website for more information on JQuery.

Note: The examples use communication with a PHP server, but any server side language will work.

AJAX Callbacks

First we have an AJAX call. In the AJAX call you setup callback handlers for the different types of events that can occur. A common misconception can be shown in the following code:

// Incorrect!
function makeAjaxCall() {
  var result = $.ajax({
    url: 'ajax/test.html'
  });

  return result;
}

The problem here is that when your browser makes an AJAX request, it can either come back successful, or as a failure. For example if you try an access a page that doesn’t exist, or if the server has an internal error. To keep things as organized as possible, AJAX requires that you create callback functions to handle the data request. The correct way is as follows:

// Correct!
function makeAjaxCall() {
  $.ajax({
    url: 'ajax/test.html',
    success: function(data) {
      alert('Horray the AJAX call succeeded!');
    },
    error: function(xhr, error) {
      alert('Holy errors batman!');
    }
  });
}

The Nature of AJAX Calls

AJAX calls can be either Asynchronous or Synchronous. Asynchronous means that the browser will make the AJAX request and continue doing other things. Synchronous means the browser will stop what it’s doing until the AJAX call completes. Here is an example of the differences in the two code wise:

// An asynchronous call
// This is the default
$.ajax({
  url: '/server.php',
  success: function(data) {
    alert('Horray the AJAX call succeeded!');
  },
  error: function(xhr, error) {
    alert('Holy errors batman!');
  }
});
// This will get called right away
myFunction();

Now for a synchronous call:

// A synchronous call
$.ajax({
  url: '/server.php',
  async: false, // set the property here
  success: function(data) {
    alert('Horray the AJAX call succeeded!');
  },
  error: function(xhr, error) {
    alert('Holy errors batman!');
  }
});
// This won't get called until the AJAX returns!
myFunction();

WARNING: Synchronous calls make it so the browser can’t do anything until the browser completes the call. This could potential lock up the browser! Only use this if you REALLY KNOW WHAT YOU’RE DOING! 99% of the time you want asynchronous AJAX calls.

Note: Synchronous calls don’t mean you can get out of not setting callback handlers. You still have to deal with the results using callbacks.

The Client->Server Communication Path

The AJAX Client Server Communication Path

This image illustrates how AJAX is used to communicate with a remote server. First the AJAX code interfaces with a browser object, which makes the actual call to the server. The server then processes the request and sends the result back to the browser, which then looks at the result of the call to determine if it needs to call the success handler, or the error handler. However, there is one issue that can prevent communication at all, which is commonly known as the same origin policy.

Note From the perspective of the server, the AJAX call will look as if the client had made the request manually. That means the server can utilize things like sessions and other client specific data.

Same Origin Policy

The same origin policy basically means that if your AJAX call is from a page hosted on http://www.mysite.com, you can’t make a call to http://www.othersite.com as illustrated here:

Same origin policy blocking a request

One way that you can get around this is through a proxy service. This is where you interface with a script on the same server, which in turn interfaces with the site you wish, through CURL calls for example. The following illustrates this proxy method in question:

Same origin proxy workaround

WARNING Note that the third party server will not see the request as coming from the client, but as coming from the server. Some servers frown upon the same IP making many calls to their servers. This could get you blocked, so verify that the site in question is okay with this setup.

Note: There are some instances where same origin policy doesn’t apply, such as Google Chrome extension calls (you have to set permissions for each site though), certain Greasemonkey calls, and Adobe Air.

Now the final concept to go over is how the server returns data for the client to interact with.

AJAX Data Return

Since it’s a very popular option, we’ll use JSON, or (J)ava(S)cript (O)bject (N)otation, to pass back the data. JSON basically looks like this:

{
    color: "red",
    value: "#f00"
}

This string can be turned into a JavaScript object, providing easy access to the server results.

WARNING Since this is valid JavaScript, many people use eval() to quickly create js objects. Please don’t do this. It opens you up to security issues if the result has malicious code in it. Always use a JSON parser that checks for secure data!

Using the previous example, we can access the different values like so:

$.ajax({
  url: '/server.php',
  // It's a good idea to explicitly declare the return type
  dataType: 'json',
  success: function(json) {
    alert("The color is: " + json.color + " and the value is: " + json.value);
  },
  error: function(xhr, error) {
    alert('Holy errors batman!');
  }
});

Notice how easy it is to access the values of the return. Another popular option is to retrieve HTML from a server and inject it into a <div> or other element. Here is an example of this:

$.ajax({
  url: '/server.php',
  // It's a good idea to explicitly declare the return type
  dataType: 'html',
  success: function(html) {
    $("#mydiv").html(html);
  },
  error: function(xhr, error) {
    alert('Holy errors batman!');
  }
});

// Some JS/HTML here

<div id="mydiv"></div>

In the case of a successful return, the contents of the <div> will be populated with the return HTML.

TODO: Dealing with securing against malicious HTML injection?

Conclusion

This concludes the community wiki post on AJAX. I hope it will be useful in helping you understand AJAX, or as an easy way to answer common questions about it.

Leave a Comment