AJAX

  • Post author:
  • Post category:AJAX
  • Post comments:0 Comments

Allows the sending of data from a webpage to the server, after the page has loaded, and the receiving of data from the webserver, without having to reload the web page. It also allows the webpage content to be updated without reloading the webpage.

<!DOCTYPE html>
<html>
<head>
  <title>Page Title</title>
  <style type="text/css">body { background-color: #00bfff; }</style>
</head>
<body>

  <p id="myParagraph">Click here to do some Ajax</p>

</body>
</html>

<script>
// add event listener to the paragraph above
document.getElementById('myParagraph').addEventListener("click",myAjaxFunction);
function myAjaxFunction(){
// create a new XMLHttpRequest object
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("myParagraph").innerHTML = this.responseText;
    }
  };
  xhttp.open("GET", "james.txt", true);
  xhttp.send();
}
</script>

james.txt

&lt;h2>This is a H2 header&lt;/h2>
&lt;p>This paragraph of text, along with the header above, came from james.txt&lt;/p>

Breaking the above down;

XMLHttpRequest methods

xhttp.abort() : will abort the Http Request
xhttp.getAllResponseHeaders() : returns all header information
xhttp.getResponseHeaders() : returns specific header information

xhttp.open(method, url, async, user, psw) : opens the request

  • method – GET or post
  • url – the location the ajax request is being sent to
  • async – true = asynchronous, false = synchronous
  • user – username (this is optional)
  • psw – password (this is optional)

xhttp:send() : for GET requests, sends information to the server
xhttp:send(string) : this is used for POST requests
xhttp:setRequestHeader() : adds key value pairs to request being sent

XMLHttpRequest object state properties (reponse)

onreadystatechange defines what function will be called when the readystate property changes. I.e. it is the current state of the XMLHttpRequest. It can be considered as a real time monitor of the progress made in completing the AJAX request.

readyState shows the state of the request in real time;

  • 0 = request not started
  • 1 = connection to the server established
  • 2 = the ajax request has been received
  • 3 = the ajax request is being processed
  • 4 = the request is finished and response is ready

responseText returns the response as a string
responseXML return the response as XML

status will return the state number of the request

  • 200 = OK
  • 404 = not found
  • …. there are other status numbers that give information

statusText returns the status text

AJAX callbacks (Callbacks in Javascript)

To understand call backs, for a moment we’ll leave Ajax and talk about what is a call back itself. Javascript is a very event driven language, and call backs are a way of preventing code executing before certain events have been carried out. Callbacks are in effects a way of controlling what code executes, and when. It is a way to ensure that code executes when it needs to, and doesn’t execute when we don’t want it to.

To explain this, here’s some simple code to start with.

<script>
  function firstFunction(){
    console.log("First Function");
  }
  function secondFunction(){
    console.log("Second Function");
  }
  
  firstFunction();
  secondFunction();
</script>

As expected we get the output in the console

So far all is great, and we get the output as expected. But consider this, what would happen if firstFunction requires some processing to happen before secondFunction executes. For example, this could be the case if firstFunction needs to make an AJAX call, which would take some time. Things would screw up if secondFunction was dependent on data from firstFunction (that hadn’t completed its tasks yet).

We can simulate this by placing a time delay in firstFunction.

<script>
  function firstFunction(){
    setTimeout( function(){console.log("First Function")}, 500 );
  }

  function secondFunction(){
    console.log("Second Function");
  }

  firstFunction();
  secondFunction();
</script>

What just happened here? We called the firstFunction, then the secondFunction, but as we can see from the console, the secondFunction was executed first.

This happened because the secondFunction didn’t know that the firstFunction had not completed it’s execution.

This is where CALLBACKS come into play.

&lt;script>

  function do2Functions(callback) {
    console.log("First Function");
    callback();
  }

  do2Functions(function() {
    console.log("Second Function");
  });
  
&lt;/script>

In the code above, the function that displays “Second Function” is sent as an argument (the call back) to the function do2Functions.

The alternative way to code the above is as below. Here we’ve simple separated the logic (into a separate function) that displays “Second Function”, but nevertheless, we have sent this function, as a parameter to the function “do2Functions”.

<script>

  function do2Functions(callback) {
    console.log("First Function");
    callback();
  }

  do2Functions(showSecondFunction);


  function showSecondFunction(){
      console.log("Second Function");
  }

</script>

This produces exactly the same results.

Call back functions are very useful in Ajax, because we can write 1 function for executing the XMLHttpRequest object, and one callback function for each task that the AJAX does.

Leave a Reply