{infiniteZest}
// Articles. Tutorials. Utilities.
Home  |   Search  |   Login  
Categories Skip Navigation Links
New / All
AJAX
Apple
ASP.NET
.NET
Git
Google / Android
Python / IronPython
Miscellaneous
SQL Server
XMLHttpRequest and AJAX on Google Suggest
Summary
This article looks at how Google Suggest uses the XMLHttpRequest object in order to provide the real-time search suggestions in an AJAX way. The actual JavaScript code used to get the XMLHttpRequest object and the function that’s called on onreadystatechange are discussed.
 
Table of Contents

The Google Suggest

Figure 1. Results for ajax from Google Suggest

Creating the XMLHttpRequest Object

Code Listing 1. Creating and Returning the XMLHttpRequest object on Google Suggest

Analyzing the JavaScript code that gets the XMLHttpRequest object

Figure 2. Analysis of getting XMLHttpRequest Object on Google Suggest

Initialize potential XMLHttpRequest object to null

Get the XMLHttpRequest object on older Microsoft browsers

Get the XMLHttpRequest object on other browsers

Return newly created XMLHttpRequest object

Using the XMLHttpRequest object

Code Listing 2. Setting up and using the XMLHttpRequest object on Google Suggest

Analyzing the JavaScript code that uses the XMLHttpRequest object

Figure 3. Analysis of Using XMLHttpRequest Object on Google Suggest

Get the XMLHttpRequest object

Prepare a request for the server

Setup the callback function

Check for the readyState and responseText

ToDo in case of non-success status

ToDo at success

Send the request

Links for XMLHttpRequest

 
Article Series
Previous Article: This is the First Article of the Series
This article is part of the Series:
Article Series: XMLHttpRequest and AJAX on Popular Sites
Next Article:
XMLHttpRequest and AJAX on maps.live.com

The Google Suggest

Google Suggest was one of the first to wow the Internet users with AutoSuggest. As you type in the characters in Google’s search box, suggestions for that term would be automatically displayed underneath the search box.

You can try Google Suggest from this link:

Google Suggest

As you can see from the image below, when you type in ajax into the Google Suggest box, you will instantly see the suggestions for a longer search string.

Figure 1. Results for ajax from Google Suggest

Figure 1. Results for ajax from Google Suggest

Let’s look at the XMLHttpRequest object that makes the above instantaneous display possible for the browser by connecting to the Google servers in the background.

Creating the XMLHttpRequest Object

The JavaScript code in Code Listing 1, gets the XMLHttpRequest object supported by the browser. This JS code is taken from the source of the Google Suggest page.

Code Listing 1. Creating and Returning the XMLHttpRequest object on Google Suggest

function ga()
{
    var a=null;

    try
    {
        a=new ActiveXObject("Msxml2.XMLHTTP")
    }
    catch(b)
    {
        try
        {
            a=new ActiveXObject("Microsoft.XMLHTTP")
        }
        catch(c)
        {
            a=null
        }
    }
    
    if(!a&&typeof XMLHttpRequest!="undefined")
        a=new XMLHttpRequest;
        
    return a
}

Analyzing the JavaScript code that gets the XMLHttpRequest object

The actual JS code behind the Google Suggest page is, of course, the ‘release’ version. All this JavaScript would be one long string without any formatting. The code has also been obfuscated by drastically changing the function and variable names. Here the function is named ga() and the variables are a, b, and c.

In the real code at Google, these names would be more meaningful and longer. But this short piece of code doing something standard is not difficult to understand at all.

Figure 2. Analysis of getting XMLHttpRequest Object on Google Suggest

Figure 2. Analysis of getting XMLHttpRequest Object on Google Suggest

The figure above shows various parts of the function returning the XMLHttpRequest object.

Initialize potential XMLHttpRequest object to null

The variable a (obfuscated name) is initialized to null. This can be checked later to see if an XMLHttpRequest object has been obtained.

var a=null;

Get the XMLHttpRequest object on older Microsoft browsers

The Microsoft Internet Explorer browser did not support the XMLHttpRequest object prior to version 7. In those browsers, you had to use ActiveXObject to instantiate an XMLHTTP object. Different older versions of IE had different ways of getting XMLHTTP object.

try
{
    a=new ActiveXObject("Msxml2.XMLHTTP")
}
catch(b)
{
    try
    {
        a=new ActiveXObject("Microsoft.XMLHTTP")
    }
    catch(c)
    {
        a=null
    }
}

Get the XMLHttpRequest object on other browsers

On all the newer versions of browsers (Internet Explorer 7, FireFox, Safari, and Opera), the XMLHttpRequest object is defined. So, if the browser is not one of the older versions of IE, it will fall through to the following code and a new object of XMLHttpRequest is created.

if(!a&&typeof XMLHttpRequest!="undefined")
    a=new XMLHttpRequest;

Return newly created XMLHttpRequest object

And finally, return the newly created XMLHttpRequest object to the calling function.

return a

Using the XMLHttpRequest object

In the above code we saw how XMLHttpRequest object is created on the Google Suggest page. The code here actually uses that object to obtain the suggestions in the background from the Google servers.

Again, the code here is the ‘release’ version of JavaScript. Though it’s the exact code that’s behind the Google Suggest page, it has been formatted to understand it better.

Code Listing 2. Setting up and using the XMLHttpRequest object on Google Suggest

function Ga(a)
{
    if(B&&B.readyState!=0&&B.readyState!=4)
    {
        B.abort()
    }

    if(B)
        B.onreadystatechange=Ha;
        
    B=ga();
    
    if(B)
    {
        B.open("GET",C+"&js=true&q="+a+"&cp="+o,true);

        B.onreadystatechange=function()
            {
                if(B.readyState==4&&B.responseText)
                {
                    switch(B.status)
                    {
                        case 403:
                        G=1000;
                        break;
                        
                        case 302:
                        
                        case 500:
                        
                        case 502:
                        
                        case 503:
                        G++;
                        break;
                        
                        case 200:
                        var b=B.responseText;
                        if(b.charAt(0)!="<"&&
                            (b.indexOf("sendRPCDone")!=-1||
                            b.indexOf("Suggest_apply")!=-1))
                        {
                            eval(b)
                        }
                        else
                        {
                            F--
                        }
                        
                        default:
                        G=0
                    }
                }
            };
            
            B.send(null)
    }
}

Analyzing the JavaScript code that uses the XMLHttpRequest object

Once you obtain the XMLHttpRequest object, you need to prepare a data request for the server and ‘open’ it. Since the suggestions are obtained asynchronously, Google Suggest page makes up function to execute once the results are obtained. This function is assigned to ‘onreadystatechange’ property of the XMLHttpRequest object. And, the object would need to ‘send’ that request.

The figure below shows various parts of using the XMLHttpRequest object.

Figure 3. Analysis of Using XMLHttpRequest Object on Google Suggest

Figure 3. Analysis of Using XMLHttpRequest Object on Google Suggest

Get the XMLHttpRequest object

First step is to get the XMLHttpRequest object, so that the Google Suggest page can communicate with the Google server.

if(B&&B.readyState!=0&&B.readyState!=4)
{
    B.abort()
}

if(B)
    B.onreadystatechange=Ha;
    
B=ga();

In the above code it’s doing checks to see if the XMLHttpRequest has already been obtained. The key code is in the last line: B=ga(), which calls the first function we discussed above to get the XMLHttpRequest object.

Prepare a request for the server

The whole reason for this code is to GET the suggestions from the Google server.

B.open("GET",C+"&js=true&q="+a+"&cp="+o,true);

In the above line, a URL is being prepared with ‘q=’. That’s the search string that the user is typing into the search box. The variable ‘a’ is passed on to this function Ga(a).

Here, the open() method on XMLHttpRequest is used in preparing the request for the server. The parameters used here are:

GET : The HTTP request method is GET. Other option is POST.

C+”&js=true&q=”+a+”&cp=”+o : This is the actual URL of the request

true : The last parameter of the open() method is true. This is the asynchronous flag, which means the request will be executed asynchronously.

Setup the callback function

A callback function needs to be set up since the request is to be executed asynchronously. Meaning a particular function will be called when the results are obtained from the server.

B.onreadystatechange=function()

The callback function is assigned to the property onreadystatechange property of the XMLHttpRequest object (which is B here).

Check for the readyState and responseText

The callback function gets called each time the readyState is changed. The readyState can have values from 0 through 4. What we are interested in is the readyState of 4 – which means the request is ‘Complete’

if(B.readyState==4&&B.responseText)

In this case, the code is also checking if there is something in the responseText, which is another property of XMLHttpRequest. In this case (for the Google Suggest), there is no point in displaying anything (like a warning/information message like ‘no results retuned’) when no results are obtained.

So, the work portions of the callback function will get executed only when the readyState is complete and there is something in the responseText.

ToDo in case of non-success status

Just because the request has been completed, it does not mean request is successful.

case 403:
G=1000;
break;

case 302:

case 500:

case 502:

case 503:
G++;
break;

Here, Google Suggest looks at various non-success HTTP status codes. Following are the meanings of these status codes:

403 : Forbidden

302 : Found

500 : Internal Server Error

502 : Bad Gateway

503 : Service Unavailable

ToDo at success

What we are interested in is the status code of 200 (which stands for ‘OK’).

case 200:
var b=B.responseText;
if(b.charAt(0)!="<"&&
    (b.indexOf("sendRPCDone")!=-1||
    b.indexOf("Suggest_apply")!=-1))
{
    eval(b)
}
else
{
    F--
}

So, if the request is a success, use the text in the responseText property of the XMLHttpRequest object. Here Google Suggest is doing an ‘eval’ on the returned text. There are, of course, different ways of showing the results that came back.

Send the request

And finally, send the request. Above postback function gets executed only after the send() method below is executed.

B.send(null)

The ‘null’ parameter for the send() method means no additional data is being sent to the server. All the query strings have been made in the open() method discussed above.

Links for XMLHttpRequest

Following are some source code and article links regarding XMLHttpRequest.

Source for XMLHttpRequest Method on window class from ASP.NET AJAX Library

Methods in XMLHttpExecutor class from the Sys.Net Namespace from ASP.NET AJAX Library

Classes from the Sys.Net Namespace from ASP.NET AJAX Library

XMLHttpRequest and AJAX on Google Suggest

XMLHttpRequest and AJAX on maps.live.com

XMLHttpRequest and AJAX on Yahoo

XMLHttpRequest and AJAX on mapquest.com

Article Series
Previous Article: This is the First Article of the Series
This article is part of the Series:
Article Series: XMLHttpRequest and AJAX on Popular Sites
Next Article:
XMLHttpRequest and AJAX on maps.live.com
Bookmark and Share This

More Articles With Similar Tags
icon-ajax-xmlhttprequest-yahoo-maps-get-object.jpg
This article looks at the code that creates XMLHttpRequest object on the Yahoo Maps and Yahoo Mail pages. This code has a clever way of iterating through the ActiveX objects on older Microsoft browsers.
icon-ajax-xmlhttprequest-live-maps-get-object.jpg
This article looks at how maps.live.com gets the XMLHttpRequest object on a given browser. It looks for either the XMLHttpRequest global object on window or looks for ActiveXObject.
icon-ajax-xmlhttprequest-mapquest-get-object.jpg
This article looks at how the JavaScript code on mapquest.com gets the XMLHttpRequest object. Here are code looks for XMLHttpRequest or ActiveXObject global objects (i.e. on the window).
This series of articles looks at how popular sites use XMLHttpRequest object in their JavaScript to provide the AJAX functionality. These articles take a look at the actual JS code used on these popular sites like Google Suggest, Yahoo, Live.com, and MapQuest.
About  Contact  Privacy Policy  Site Map