AJAX

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:

     request.open('GET', 'http:someurl.somewhere/something.php', true);
  request.send();

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.


<html>
   <head>
      <script>

      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.');
                }
            }
         };
         request.open('GET', 'responder.php', true);
         request.send();
      }

      </script>
   </head>
<body>

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

</body>
</html>

response.php just looks like this:

<?php
echo ("Here is the response");
?>

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

Comments

Popular posts from this blog

Just Enough Python

Learn to code with C

Introduction to Python by Andrew Ng