Click here to Skip to main content
6,295,667 members and growing! (9,981 online)
Email Password   helpLost your password?
Web Development » Ajax and Atlas » General     Intermediate License: The Code Project Open License (CPOL)

Understanding AJAX

By Nawaz Ijaz

Let's cook up a simple AJAX example
Javascript, XML, HTML, Windows, Visual Studio, Ajax, IIS 5.1, IIS 6, Dev
Version:2 (See All)
Posted:8 Oct 2006
Views:21,520
Bookmarked:20 times
Announcements
Loading...
 
Search    
Advanced Search
printPrint   Broken Article?Report       add Share
  Discuss Discuss   Recommend Article Email
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

4
3 votes, 42.9%
5
Generating Random nos using AJAX

Introduction

Just imagine a very massive webpage providing a lot of functionalities with lot of data, all coming from the server. Now the user wants to get some information from the server that may affect only a 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 up 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 our HTML page (showRandomNos.html) will be updated instead of getting the whole page refreshed.

Using the Code

Our first page is just an 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 shown 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, we've to make a browser specific object such as in case of Internet Explorer; we will create it as shown 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 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 as listed 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:

// FOR TEXT Response
xmlHttpReq.responseText;

// FOR XML Response
xmlHttpReq.responseXML;      

In the end, let's have a look at 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!

History

  • 8th October, 2006: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Nawaz Ijaz


Member
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
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 2 of 2 (Total in Forum: 2) (Refresh)FirstPrevNext
GeneralTags Pinmembercykophysh3922:21 10 Oct '06  
GeneralRe: Tags PinmemberNawaz 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: Deeksha Shenoy
Copyright 2006 by Nawaz Ijaz
Everything else Copyright © CodeProject, 1999-2009
Web18 | Advertise on the Code Project