From The Ground Up – Ajax 1 – Introduction

This is the first in a series of posts related to Ajax technologies, an attempt to explain, what, why, when and how to use it.

Assumptions

You know some HTML & CSS

You know some Javascript

Best if you also know some jQuery

You have a web server installed in your computer (XAMPP, IIS, or be using   Visual Studio )

 

Feel free to add input in the coments section!

 

Disclaimer

What?

Asyncronous Javascript and XML – aka AJAX:

Is a set of technologies that can be used to implement a Web application that communicates with a server in the background 1

Some of these technologies are:

  • XMLHttpRequest object (to exchange data asynchronously with a server)
  • JavaScript/DOM (to display/interact with the information)
  • CSS (to style the data)
  • XML (often used as the format for transferring data) / JSON
  • JavaScript to bring these technologies together

It is also used to refer to AJAJ (change XML for JSON – more on this later).

Why?

In the beginning, pages where entirely static. That meant each time you wanted to show something different, you had to click on a new link and request a new page from the server.

As technology progressed, and applications became more dynamic, new forms of interacting with the web and its content came round. From the development point of view, mainly Javascript (completely unrelated to Java) added a lot more behavior to websites by allowing interaction with the content in those pages.

Along came the need to optimize information retreival, and with this, the somewhat obvious notion of not having to refresh the entire page each time a small part of the content needed to change/refresh (think ads, information in a table, getting more results for a search, etc).

One solution for this was AJAX, and it mainly consisted of making Asyncronous (no blocking of the current thread, hence the UI) calls to the server to retrieve or send data, allowing to reduce network traffic by not having to send/receive all the HTML each time something needed to be updated, and instead only sending/receiving the required information.

When?

Here are a few scenarios where one would use AJAX:

  • When needing to refresh a portion of a webpage.
  • When needing to retreive information from the server to load a list/dropdown/table/display information to the user.
  • When needing to send information to the server and avoid refreshing the webpage.

How?

Overview of an ajax request flow:

AJAX call flow

 

So let’s do a very simple website to apply ajax.

  1. Create a folder in your server’s root (ie: c:/inetpub/wwwroot/ajaxtest)
  2. Create an index.html file which contains the main code.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>FTGU Ajax-1</title>
    <script src="ajaxTest.js" type="text/javascript"></script>
</head>
<body>
    <div id="ajaxContent">
        This is a sample text
    </div>
    <button onclick="changeAjaxContent()">Click me!</button>
</body>
</html>
  1. Create the html we are going to fetch from the server
<div>
    This is the text I retreived with AJAX! Woohoo!
</div>

We will put the ajax javascript inside the ajaxTest.js file.

  1. Let’s write the actual javascript code that will make the magic happen. In itself it has 3 parts:
    1. Create the actual XMLHttpRequest
    2. Specify a callback function to process the server’s response
    3. Initialize the request
    4. Send it
function changeAjaxContent() {
    var request;

    if (window.XMLHttpRequest) {
        // create the XMLHttpRequest
        // code for IE7+, Firefox, Chrome, Opera, Safari
        // this should be the standard nowadays, actually they comprise ~80%+ of all used browsers.
        request = new XMLHttpRequest();
    } else {
        // code for IE6, IE5 - this should be no longer necessary. IE6 users are approximately 2% of all browser users.
        request = new ActiveXObject("Microsoft.XMLHTTP");
    }
    //callback function for when response is received from the server.
    request.onreadystatechange = function() {
        if (request.readyState == XMLHttpRequest.DONE ) {
            if(request.status == 200){
                document.getElementById("ajaxContent").innerHTML = request.responseText;
            }
            else if(request.status == 400) {
                alert('There was an error 400')
            }
            else {
                alert('something else other than 200 was returned')
            }
        }
    }
    request.open("GET", "ajaxDiv.html");
    request.send();
}

Let’s go over the previous javascript code line by line:

In lines 08/11 we instanciate the XMLHttpRequest object2.

A great resource to learn about javascript objects and functions is Mozilla Developer Network. You should bookmark the site and keep it as reference since it will help with a lot of functions.

In line 14 we specify the callback function. This gets called several times during the lifetime of the request. Read about the possible states here.

Basically, the request’s state changes when initializing it, when sending the request, while getting the data, and when all data has been retreived. In this simple case, we only want to do something when all data has been received.

Line 15 makes sure the response from the server is ready.

Line 16 checks that we received OK from the server. IANA maintains the standard meaning of the HTTP Status codes, and you can check what each code means here, eventually acting differently depending on the status code the response sent.

Line 17 if OK, then replace the placeholder’s HTML with the HTML we got from the server.

Lines 19-24 alert us otherwise

In Line 27 we initialize the request, specifying the HTTP Method (“GET”, “POST”, “DELETE”, or other), and the resource we are requesting (ajaxDiv.html);

Finally in Line 28 we send the request to the server. What server? Well it will depend on what resource we specified. Since we didn’t specify a full URL, we will get the resource relative to the current path.

In our case it will be something like http://localhost/

So try it out! Run the website, click the button and see what happens.

You can download the code for part 1 here.

In Part 2 we’ll see how to do the same with jQuery, and we will then move on to more interesting things.

 

1 Ajax_(Programming) – Wikipedia
2 XMLHttpRequest – Mozilla Developer Network

Leave a Reply

Your email address will not be published. Required fields are marked *