Ajax 101

Ajax is all about the XmlHttpRequest request, or XHR request for short. To set up a really basic demonstration of this, create a script.js file with the following request variable to work with.

You'll also need to create two more file: an HTML file which references the script.js and the data.txt file which the request is getting; just add a little bit of text to the file and save it to the same directory.

var request = new XMLHttpRequest();
request.open('GET', 'data.txt', true); // true is for asynchronous

If you run your HTML file and view the console of your browser, you'll see the XmlHttpRequest object which lists a bunch of properties. There are two key properties that we need to consider; status and readyState. We need the status code to be 200, which means the script was able to find the data.txt file. readyState has a value from 0 to 4. If readyState has value of 4, the asynchronous request has been received and we can do something with it.

Let's add a function which binds to the onreadystatechange property and includes a check for the two key properties. If this is OK, we can use JavaScript's document.writeln method to output the responseText to our page.

// continuing from the snippet above
request.onreadystatechange = function() {
  if((request.readyState === 4) AND (request.status === 200)) { //note

Note: the AND above should be a double ampersand &&. This was only added to prevent this page from encoding it


Comments are closed.