Broad Network


Receiving Response to Ajax Request

Ajax Web Technology Explained – Part 2

Forward: This is part 2 of my article series, Ajax Web Technology Explained. It is the last part. In part 1 we saw how to make the request. In this part we shall see how to receive the request at the client browser.

By: Chrysanthus Date Published: 30 Jul 2012

Introduction

This is part 2 of my article series, Ajax Web Technology Explained. It is the last part. In part 1 we saw how to make the request. In this part we shall see how to receive the request at the client browser.

Well, it is possible that when you make a request at the browser, the reply (response) may never come back to the browser. So, it might be good to do some timing to abort the request if there is no response after some time limit. We shall see how to do this timing at the end of this part of the series.

Objectives of the Ajax Object revisited
In part 1 of the series, we saw that the following three objectives have to be accomplished by Ajax:

- Open (start) a connection between the client computer and the server.
- Send the request for the information (text) the user needs.
- Wait for the response and receive it.

The Ajax object you create has properties, methods and an event handler that accomplishes these objectives. The first objective is achieved by the Ajax object open() method; we saw this. The second objective is achieved by the Ajax object send() method; we saw this as well. The third objective is achieved mainly by an event handler called the onreadystatechange event handler. You are the one who writes the statements for the event handler. All you do is that you simple put statements in the function of the handler that will make use of the text (data) replied from the server. We shall see an example below.

Important Methods of the Ajax Object
I have talked about two important Ajax object methods, which are the open() and send() methods. Another important method, we shall talk about is called the abort() method. The method is used to abort the Ajax request after a time limit. We shall see an illustration below. Ajax request is considered to have been made after the statement of the Ajax object send() method has been executed at the client.

Remember, for the GET method, the send() statement must immediately follow the open() statement. And for the POST method, you need to have the open() statement, immediately followed by the setRequestHeader() statement, immediately followed by the send() statement.

Important Properties of the Ajax Object
The readyState property
When you create the Ajax object, it inherently has a property called the readyState property (just as it inherently has its methods). This property had already been declared. All you have to do is to learn how to use it, and that, I show you in this section.

The readyState property will acquire the integer, 0, 1, 2, 3, or 4 depending on the stage of the execution of the Ajax request, without your intervention. These numbers have the following meaning:

0: uninitialized
1: loading
2: loaded
3: interactive
4: complete

The onreadystatechange event is triggered each time the value (integer) of the readyState property changes. The most important of these integers is 4, when the browser has the reply from the server. The statements you have in the function of the onreadystatechange event are executed, when the readyState property is 4

With Ajax, the reply is either text or an XML document. I will not consider the case of XML document in this series. The text may consist of discrete data joined into a string. It is up to your code at the client browser to extract each datum. The example below will just display the text received. The following code segment shows how to use the onreadystatechange event and the readyState property:

    myAjax.onreadystatechange=function()
        {
            if (myAjax.readyState == 4)
                {
                    alert(myAjax.responseText);
                }
        }

The first line above has the Ajax object you created. This is followed by a dot, and then the word, onreadystatechange, thus beginning the event handler. The event handler or its function has to be defined. So, after the beginning, you have the assignment operator, and then the function definition, which has “function()” and then the enclosing {}.

Inside the function, you check if the readyState is 4 meaning that the browser has got text from the server. If the browser has got text, then the if-block code should make use of the text. In our case above the text received is simply displayed to the user in an alert box.

The responseText Property
The Ajax object you create has another inherent property called the responseText property. When the text from the server has reached the browser, it is assigned to this property. This happens when the readyState becomes 4. To access the received text, type:

                      myAjax.responseText

which begins with the Ajax object you created followed by a dot and then the word, responseText. This section clarifies what you have in the if-block of the above code segment.

If you want to react to the other readyState property integers, then you would need one if-statement for each integer, inside the onreadystatechange event handler.

So, make use of the reply when the readyState property is 4 in the onreadystatechange event, which is triggered each time the value of the readyState property changes.

The status property
Now, when the readyState property is 4, this indicates that the Ajax object has something from the server. Now, the text received may not be what you want. It might be an error message, sent by the server. The error message might be that something is wrong in the server.

There is another Ajax object property, which indicates that your reply (text) is what you wanted or an error. This is the status property. It receives integers as values from the server, not from you the user or coder. If it received 200 it means the request was successful and you have what you want. If it received 404, it means the request failed. There are other integers it can receive indicating other things. The most important of these is 200, indicating that you have got what you wanted. Any of these number that arrived is assigned to the status property. If you have not got what you wanted, you do not have to process the information received. You can ignore it and issue an your own custom error message to the user. The following code segment illustrates the use of the status property.

    myAjax.onreadystatechange=function()
     {
        if (myAjax.readyState == 4)
         {
            if (myAjax.status == 200)
             {
                 alert(myAjax.responseText);
             }
         }
     else
        {
         //alert error – to the client.
        }
     }

So if you were coding our example with the POST method, then this is what you would have:

    var myAjax;

    if (window.XMLHttpRequest)
            {// code for IE7+, Firefox, Chrome, Opera, Safari
                myAjax = new XMLHttpRequest();
            }
    else
            {// code for IE5, IE6
                myAjax = new ActiveXObject("Microsoft.XMLHTTP");
            }

    myAjax.onreadystatechange=function()
     {
        if (myAjax.readyState == 4)
         {
            if (myAjax.status == 200)
             {
                 alert(myAjax.responseText);
             }
         }
     else
        {
         //alert error – to the client.
        }
     }

    myAjax.open("POST", "http://www.somewebsite.com/sendtext.php", true);
    myAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    myAjax.send("fname=John&lname=Smith");

Note that the function of the onreadystatechange event is not executed as the web page is loaded. It can only be executed after the request has been sent to the server and a feedback received at the browser.

We are not yet at the end of the story. What about the case when you make a request and you never get a response, because of some possible unexplained problem beyond your client computer? That next.

Timing Out the Request
It is possible that when you make a request the response might take a very long time to arrive; it is also possible that the response might never arrive. The request is completely made when the statement for the send() method has been executed. After this point the client computer (browser) waits for the response.

You can always abort the request, after a particular time limit. If you abort a request, you will not receive a response.

As we saw above, the Ajax function has an abort() method. To abort a request, just call

                   myAjax.abort();

where myAjax is the Ajax object you created. Before you do this, you will have to set a timer function. This timer function will call the abort() method. The syntax for the timer function is:

              setTimeout(code,millisec);

The first parameter is the code that will be executed after the time limit. The second parameter is the time limit in milliseconds; it is the time after which the first parameter code is executed. In our case, if you want the Ajax request to be aborted after 20 seconds, you would have,

              setTimeout("myAjax.abort();",20000);

Note that the code of the first argument is in quotes. It has to be like that. The above statement has to be placed immediately below the statement of the send() function.

Important: Many browsers do not support the abort() method.

Ajax Function
If you type all what I have said in the JavaScript of your body element, it would be executed as your web page containing the script is executed. To avoid this, you can put all the Ajax statements in a JavaScript function and call that function as you would call any JavaScript function anywhere in your script. So the above code segment can be put in a function as follows:

function ajaxFn()
    {
        var myAjax;

    if (window.XMLHttpRequest)
            {// code for IE7+, Firefox, Chrome, Opera, Safari
                myAjax = new XMLHttpRequest();
            }
    else
            {// code for IE5, IE6
                myAjax = new ActiveXObject("Microsoft.XMLHTTP");
            }

         ---
            etc.
         ---

    }

You can call the function, ajaxFn(), from anywhere in your script. In many case you would want to assign the reply, that is, myAjax.responseText to a global variable. That should be done in the innermost if-block of the onreadystatechange event handler.

Encoding the Sending Data Name/Value Pairs
By the way, the sending data is known as the Query String. If your names and values of the sending data has special characters such the “&” and spaces, then you have to encode each name and value before sending. At the server decoding has to be done. I will not cover that in this series. Consult some other document for this; it is important, but it is a simple thing to do once you know what you have to do.

And that is it. We have come to the end of the story, so far as Ajax at the client is concerned. Ajax at the server does not entail much, and depends on the language e.g. Perl or PHP; it does not depend on any new standard. I intend to write an article on Ajax at the Server next.

Chrys

Related Links

Major in Website Design
Web Development Course
HTML Course
CSS Course
ECMAScript Course
NEXT

Comments

Become the Writer's Fan
Send the Writer a Message