5,702,921 members and growing! (21,052 online)
Email Password   helpLost your password?
Web Development » Ajax and Atlas » General     Intermediate License: The Code Project Open License (CPOL)

Learning ajax with xmlhttp object

By sathesh_pandian

It’s a reference for beginners who like to learn ajax.
Javascript, XML, HTML.NET 1.0, .NET 1.1, .NET 2.0, WinXP, Windows, .NET, .NET 3.0, Ajax, Visual Studio, VS.NET2002, VS.NET2003, VS2005, Dev

Posted: 27 Aug 2007
Updated: 27 Aug 2007
Views: 10,445
Bookmarked: 24 times
Announcements
Loading...



Search    
Advanced Search
Sitemap
16 votes for this Article.
Popularity: 4.39 Rating: 3.65 out of 5
1 vote, 6.3%
1
1 vote, 6.3%
2
5 votes, 31.3%
3
2 votes, 12.5%
4
7 votes, 43.8%
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

What is AJAX?

AJAX, an acronym for Asynchronous JavaScript and XML, is a web development technique for creating interactive web applications. The intent is to make web pages feel more responsive by exchanging small amounts of data with the server behind the scenes, so that the entire web page does not have to be reloaded each time the user makes a change. This is meant to increase the web page's interactivity, speed, and usability.

Creating the Object

Creating an instance of the XMLHttpRequest object is important for ajax.It differs for browsers.

For Safari and Mozilla:

var XmlHttp = new XMLHttpRequest();

For IE:

var XmlHttp = new ActiveXObject("Microsoft.XMLHTTP");

The object reference returned by both constructors is to an abstract object that works entirely out of view of the user. Its methods control all operations, while its properties hold, among other things, various data pieces returned from the server.

Object Methods

Instances of the XMLHttpRequest object in all supported environments share a concise, but powerful, list of methods and properties. The following table shows the supported methods and their jobs.

Common XMLHttpRequest Object Methods

Method Description
abort() Abort the current request
getAllResponseHeaders() Get the complete set of headers (labels and values) as a string
getResponseHeader("headerLabel") Get the string value of a single header label
send(content) Transfers the request, optionally with postable string or DOM object data
setRequestHeader("label", "value")

Sets a label/value pair to the header to be sent with a request

Example for creating the XMLHTTP object:

<script language="javascript">
  //Global XMLHTTP Request object

var XmlHttp;
//Creating and setting the instance of appropriate XMLHTTP Request object to 

//a "XmlHttp" variable  

function CreateXmlHttp()
{
 //Creating object of XMLHTTP in IE

 try
 {
  XmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
 }
 catch(e)
 {
  try
  {
   XmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
  } 
  catch(oc)
  {
   XmlHttp = null;
  }
 }
 //Creating object of XMLHTTP in Mozilla and Safari 

 if(!XmlHttp && typeof XMLHttpRequest != "undefined") 
 {
  XmlHttp = new XMLHttpRequest();
 }
}
</script>

The open method is to specifies the attributes like URL,send method etc.

Method Description

open( method, URL )

open( method, URL, async )

open( method, URL, async, userName)

open( method, URL, async, userName, password)

Assigns destination URL, method, and other optional attributes of a pending request

Two main required parameters are the HTTP method you intend for the request and the URL for the connection. For the method parameter, use "GET" on operations that are primarily data retrieval requests; use "POST" on operations that send data to the server, especially if the length of the outgoing data is potentially greater than 512 bytes. The URL may be either a complete or relative URL.

An important optional third parameter is a Boolean value that controls whether the upcoming transaction should be handled asynchronously. The default behavior (true) is to act asynchronously, which means that script processing carries on immediately after the send() method is invoked, without waiting for a response.

If you set this value to false, however, the script waits for the request to be sent and for a response to arrive from the server. While it might seem like a good idea to wait for a response before continuing processing, you run the risk of having your script hang if a network or server problem prevents completion of the transaction. It is safer to send asynchronously and design your code around the onreadystatechange event for the request object.

The following generic function includes branched object creation, event handler assignment, and submission of a GET request. A single function argument is a string containing the desired URL. The function assumes that a global variable, req, receives the value returned from the object constructors. Using a global variable here allows the response values to be accessed freely inside other functions elsewhere on the page. Also assumed in this example is the existence of a processReqChange() function that will handle changes to the state of the request object.

var requestUrl = "WebForm2.aspx" + "?SelectedCountry=" + (selectedCountry);
 CreateXmlHttp();
 
 // If browser supports XMLHTTPRequest object

 if(XmlHttp)
 {
  //Setting the event handler for the response

  XmlHttp.onreadystatechange = HandleResponse;
  
  //Initializes the request object with GET (METHOD of posting), 

  //Request URL and sets the request as asynchronous.

  XmlHttp.open("GET", requestUrl,  true);
  
  //Sends the request to server

  XmlHttp.send(null);  
 }

It is essential that the data returned from the server be sent with a Content-Type set to text/xml. Content that is sent as text/plain or text/html is accepted by the instance of the request object however it will only be available for use via the responseText property.

Object Properties

Property Description
onreadystatechange Event handler for an event that fires at every state change
readyState Object status integer:
0 = uninitialized
1 = loading
2 = loaded
3 = interactive
4 = complete
responseText String version of data returned from server process
responseXML DOM-compatible document object of data returned from server process
statusText String message accompanying the status code

Another property is status.

This will intimates the status of the request.

refer the article" Dropdown Box Using AJAX" for complete list of status.

I hope this article will help the learners of the ajax to understand the xmlhttp object.

License

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

About the Author

sathesh_pandian


have been working in dotnet technologies for the last 4 years.
Occupation: Team Leader
Company: Zylog systems pvt limited
Location: India India

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   
  (Refresh) 
-- There are no messages in this forum --

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

PermaLink | Privacy | Terms of Use
Last Updated: 27 Aug 2007
Editor:
Copyright 2007 by sathesh_pandian
Everything else Copyright © CodeProject, 1999-2008
Web18 | Advertise on the Code Project