Beginners Guide to AJAX

Follow Roger Facebooktwittergoogle_pluslinkedinrss

What is AJAX?

AJAX is magic. It lets developers retrieve information from the server at runtime without a page reload. This means that a page can change in the background while a user is interacting with the page. The most well-known example is Google Suggest – when you start typing a search query in the Google search field, a drop-down with suggested searches appears. This drop-down is generated using AJAX.

AJAX is an acronym for “Asynchronous JavaScript and XML”. So, what is “Asynchronous”? Asynchronous means one input/output (I/O) process can continue before another’s transmission is completed. In other words, on the browser side the page remains rendered while in the background the application makes a request from the server. Conversely, “Synchronous” means you wait for the page to render while the request is being completed. That’s enough on the semantics. Read the remainder of this post, then come back and reread this description.

Ancient Browser Compatibility

Be patient. The code is coming. First, a short history lesson – you need this to understand the bits we have to add for cross-browser compatibility.  AJAX originated as a Microsoft Internet Explorer ActiveX object called XMLHTTP. Other browsers later added the XMLHttpRequest class. Internet Explorer 7 added XMLHttpRequest. So, in order for your code to remain compatible with browsers older than  IE7, you need to offer the ActiveX object.

 
 var httpRequest;
 if (window.XMLHttpRequest) { // Modern Browsers
 httpRequest = new XMLHttpRequest();
 }
 else if (window.ActiveXObject) { // IE 6 and older
 httpRequest = new ActiveXObject("Microsoft.XMLHTTP");

 }

The code above is just to demonstrate the cross-browser bits. We need to add some lines for production code.

 HTTP Verbs

If you have built a form that reads or writes to the server, you are likely familiar with GET and POST – the values that can be set for the method attribute in forms. These methods are also known as verbs. If you are not familiar with creating HTML forms, read on; I think things will become more clear. The HTTP standard allows for 9 verbs: GET, POST, HEAD, OPTIONS, PUT, PATCH, DELETE, TRACE and CONNECT. For the purposes of this post I am not going into the details on verbs. We’ll stick with GET (basically “Read”) and POST (“Write”). In fact, in our example, we’ll use GET. GET is what your browser uses when you request a web page.

Sending a Request to the Server

Two lines are required in order to make a request of the server. The first uses the open() method of the JavaScript XMLHttpRequest object. The second uses its send() method.

httpRequest.open('GET', 'http://www.example.org/some.file', true);
httpRequest.send(null);

When I first started with JavaScript I had trouble getting my head around concepts like this request. So, hopefully I can help you avoid the same struggle. XMLHttpRequest is a built-in JavaScript class. In my example, we instantiated an object, httpRequest, on that class. The methods open() and send() are functions (functions within an object are called methods) within that class. To better understand JavaScript Objects, read my post about them – JavaScript Objects.

open()

The open() method accepts the parameters as follows:

open(
DOMString method,
DOMString url,
optional boolean async,
optional DOMString user,
optional DOMString password
)

I included the first three parameters.

The first parameter is the method or verb (see the previous section). Be sure to use the HTTP standard of all uppercase for the method; some browsers’ JavaScript engines throw an error otherwise. The second is the URL of the resource we are accessing. The third is a Boolean (true or false) indicating whether or not to make the request Asynchronous; yes, the “A” in AJAX stands for Asynchronous, and you can override it. Setting the value to “false” means that  the send() method won’t return until after the response is complete – making the connection/request Synchronous.

send()

The send() method is used to send data to the server. For the POST method this would include any data the server side needs in order to complete the request. i.e. form data. The format of this data must be what the server is expecting. Documents, JSON, SOAP, or query string are typical. Since we are using GET, I set the send data to NULL (basically a controlled way of sending empty).

Handling the Response

We need to receive the response from the server, check its status, then, if all is OK programmatically handle the response. The event on the XMLHttpRequest Object that handles the response is onreadystatechange. We set this event to a function that specifies what will happen once the server response is complete.

function handleResponse() {
    if (httpRequest.readyState === 4) {
        if (httpRequest.status === 200) {
            alert(httpRequest.responseText);
} else {
            alert('There is a problem with the request or response.');
}
    }
}

The readystate passes through 5 stages (counted on a zero base): 0 – Waiting or uninitialized, 1 – loading, 2 – loaded, 3 – interactive (user may interact with the response), 4 – complete. Our function above waits until the readystate is complete, at stage 4. When readystate is at complete, we check the status. A status of 200 is “OK”, which is what we want on GET request. The other possibility is 404 – “Not Found”. In the function above I simply send the response to an alert box, to indicate success.

All Together Now (the complete code)

var httpRequest;
document.getElementById("ajaxLink").onclick = function() { makeRequest('http://www.example.com/test.html'); };
function makeRequest(url) {
    if (window.XMLHttpRequest) { // Mozilla, Safari, ...
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 6 and older
try {
            httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
        catch (e) {
            try {
                httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
            catch (error) {}
        }
    }

    if (!httpRequest) {
        alert('Giving up :(  Cannot create an XMLHTTP instance');
return false;
}

httpRequest.onreadystatechange = handleResponse;
httpRequest.open('GET', url);
httpRequest.send();
}

function handleResponse() {
    if (httpRequest.readyState === 4) {
        if (httpRequest.status === 200) {
            alert(httpRequest.responseText);
} else {
            alert('There was a problem with the request.');
}
    }
}

Conclusion

I hope that this post is helpful. I spent much time trying to figure out the technologies described here. My intent was to put all the things I found in various places in one concise post. Keep in mind that I attempted to simplify things. I will write a more advanced post in the future.

Please post ideas, suggestions, questions, or ways that I can improve this post, in the comments. I will watch them.

Thanks for reading!

Share with your social networks Facebooktwittergoogle_plusredditpinterestlinkedinmail


Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>