Thursday, 17 March 2016


This is a very quick introduction to AJAX which may be expanded at a later date.

AJAX is a great way to update web pages without having to reload the content of that page.
It's name stands for Asynchronous Javascript and XML and these days is a bit of a a misnomer because it often does not involve XML (and it doesn't have to be asynchronous).

Basically, it is a set of Javascript functions that lets you send a message to another page on the network (using the normal HTTP protocol) and receive a response. The web page that receives that response can then update itself with this data.

It comprises of three parts: first you set up a request, then you send it and finally you receive the response and do something with it. Here's how it's done.

You first create an object of the type XMLHttpRequest:

   request = new XMLHttpRequest();

next you have to tell it what to do when it receives a response by giving it a function to run when the response arrives.

   request.onreadystatechange = function(){ /*function code goes here*/};

Here we've defined an anonymous function.

The next step is to call the open method, where the url of the web resource is define,  and then the send method, which actually send the request:'GET', 'http:someurl.somewhere/something.php', true);

The parameters for the open method are the http method (GET in the case), the url of the file we want to call (assumed to be a php file, here) and a boolean which defines whether the request is asynchronous or not. Here it is asynchronous, if we set the parameter to false the request would wait until a response was received before completing (this is normally not a good idea as the web page will become inoperative until the response comes back).

Here is a complete example of a web page with a request.


      function makeRequest(){
         request = new XMLHttpRequest();

         request.onreadystatechange = function(){
            if (request.readyState === XMLHttpRequest.DONE) {
                if (request.status === 200) {
                  div1 = document.getElementById("div1");
                  div1.innerHTML = request.responseText;
                } else {
                   alert('There was a problem.');
         };'GET', 'responder.php', true);


   <button onclick="makeRequest()">Press me</button>
   <div id="div1"></div>


response.php just looks like this:

echo ("Here is the response");

Things can get more complicated but this is basically how AJAX works.

No comments:

Post a Comment