5,692,513 members and growing! (15,867 online)
Email Password   helpLost your password?
Web Development » Ajax and Atlas » General     Intermediate

Understanding AJAX

By Nawaz Ijaz

Lets cook a simple AJAX example
Javascript, XML, HTML, Windows, Visual Studio, Ajax, IIS 5, IIS 5.1, IIS 6, IE 6.0, IE 5.5, IIS, IE, Dev

Posted: 8 Oct 2006
Updated: 8 Oct 2006
Views: 18,971
Bookmarked: 18 times
Announcements
Loading...



Search    
Advanced Search
Sitemap
7 votes for this Article.
Popularity: 2.01 Rating: 2.38 out of 5
1 vote, 14.3%
1
1 vote, 14.3%
2
2 votes, 28.6%
3
0 votes, 0.0%
4
3 votes, 42.9%
5
Note: This is an unedited contribution. If this article is inappropriate, needs attention or copies someone else's work without reference then please Report This Article

Generating Random nos using AJAX

Introduction

Just imagine a very massive webpage providing lot of functionalities with lot of Data, all coming from the server. Now the user wants to get some info from the server that may affect only the small portion of this page but when he submits his request, the whole page renders again unnecessarily, taking lot of time and populating each and every thing again.
This has been a very irritating problem in the past but now, AJAX (Asynchronous JavaScript And XML) has come up as a Solution of the whole page rendering. With the blessings of AJAX, we can update/refresh only the necessary part of our webpage instead of rendering the whole page itself.

Our GOAL in this Example

Our aim is to get familiar with AJAX. So here we are going to cook a very simple example by focusing on the usage of AJAX rather than making the business logic and presentation complex by involving Database connectivity or other complex logics. (Sure we all already know Databases, even if we don't know we will learn that some other time).

We'll generate random numbers on the Server (generateRandomNos.asp) and then we will call this server side code on our simple HTML page (showRandomNos.html) by means of AJAX. We'll notice that only the part of out HTML page (showRandomNos.html) will be updated instead of getting the whole page refreshed.

Using the code

Our first page is just a HTML page that displays randomly generated numbers when user clicks on the button "Generate Random numbers" BUT the science used here is AJAX. Only a small division is updated instead of rendering the whole page to accomplish the user's request.

   onclick='JavaScript:generateRandomNumbers("generateRandomNos.asp")'

On the button's Onclick event, we call a JavaScript function and pass the URL of the .asp page (that will generate the Random numbers at the server) like above;

   function generateRandomNumbers(targetURL) 
   {
        var xmlHttpReq = false;
        // FOR IE

        if (window.ActiveXObject) {
            xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
        }
        // FOR OTHER BROWSERS

        else if (window.XMLHttpRequest) {
            xmlHttpReq = new XMLHttpRequest();
        }

        xmlHttpReq.open('POST', targetURL, true);
        xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xmlHttpReq.onreadystatechange = 
            function() { // START OF Callback function

                if (xmlHttpReq.readyState == 4) {
                    document.getElementById("result").innerHTML = xmlHttpReq.responseText;
                    document.getElementById("generationStatus").innerHTML= "Done !!";
                }
                else
                {
                    document.getElementById("generationStatus").innerHTML= "Generating Random numbers...";
                }
            } // END OF Callback function

        xmlHttpReq.send();
     }

For processing the server side code, we need to send a request to the server. As AJAX is a browser specific technology so we've to make a browser specific object such as in case of I.E; we will create it like below;
        new ActiveXObject("Microsoft.XMLHTTP");

Now we will call the server side code using the XMLHttpRequest object.

        xmlHttpReq.open('POST', targetURL, true);
Different states of our xmlHttpRequest object will let us know that how far we have reached. Its readyState 4 tells the browser that our request has successfully been completed and control has been returned to the browser. readyStates can be of four different types such as below;
        0 = uninitialized
        1 = loading
        2 = loaded
        3 = under process
        4 = complete
        if (xmlHttpReq.readyState == 4) {
            document.getElementById("result").innerHTML = xmlHttpReq.responseText;
            document.getElementById("generationStatus").innerHTML= "Done !!";
        }
        else
        {
            document.getElementById("generationStatus").innerHTML= "Generating Random numbers...";
        }

We can also get the server's response in the form of TEXT or XML such as below;

        
        // FOR TEXT Response

            xmlHttpReq.responseText;
        // FOR XML Response

            xmlHttpReq.responseXML;
            

In the End, Lets have a look on our Server side code below; It just generates random numbers using rnd method

        for i = 1 to 9999
            Randomize()
            response.Write(rnd)
        next

We've successfully cooked our first AJAX example and to taste it, just place both the files on your web server and then run the web page showRandomNos.html... Enjoy :-)

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Nawaz Ijaz


Like typical Piscean, Nawaz Ijaz is a dreamer and a very sensitive guy indeed. He loves to take challenges. His aim is to become the master in his field. He is currently working as a Software Engineer at NetSol Technologies (a CMMI Level 5 Organization). He believes on learning Technologies rather learning tools. He feels comfortable while programming under any platform. However he is keener to work on Web Application Development. Previously, he has also made various Plug-ins for Adobe Acrobat Exchange during his stay at KAPS Computing.

Nawaz Ijaz has done BS (hons) in computer sciences and planning to do some specializations in the same field in near future.
Occupation: Web Developer
Location: Pakistan Pakistan

Other popular Ajax and Atlas articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 2 of 2 (Total in Forum: 2) (Refresh)FirstPrevNext
GeneralTagsmembercykophysh3922:21 10 Oct '06  
GeneralRe: TagsmemberNawaz Ijaz22:31 10 Oct '06  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 8 Oct 2006
Editor:
Copyright 2006 by Nawaz Ijaz
Everything else Copyright © CodeProject, 1999-2008
Web11 | Advertise on the Code Project