Go4Expert

Go4Expert (http://www.go4expert.com/)
-   JavaScript and AJAX (http://www.go4expert.com/articles/javascript-tutorials/)
-   -   Xmlhttp in JavaScript (http://www.go4expert.com/articles/xmlhttp-in-javascript-t454/)

pradeep 3Oct2005 22:54

Xmlhttp in JavaScript
 
Xmlhttp is hot these, with the advent of AJAX.Xmlhttp is mainly used on the client-side to query or fetch blocks of data from the server.A typical example would be when in a sign up form the user selects the country the states for the selected country is automatically populated in the state dropdown.
Xmlhttp has two modes of operation, synchronous and asynchronous. In the synchronous mode,the browser window is locked till the operation is complete, as a result the user has to wait for the operation to complete even to scroll up/down the page, in contrast to synchronous mode synchronous mode is more preffered because, it works in background with affecting the other functions of the browser.

The example code below shows how to create the Xmlhttp object:

Code: JavaScript

var xmlhttp=false;
 try
 {
   xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); /* for IE < 5 */
 }
 catch (e)
 {
    try
    {
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    catch (E)
    {
    xmlhttp = false;
    }
 }
 
 /* mozilla & opera */
 if (!xmlhttp && typeof XMLHttpRequest!='undefined')
 {
   xmlhttp = new XMLHttpRequest();
 }

The basic methods of the Xmlhttp object are:

.open(string method,string url,bool async) /* opens the connection to the server */
.send(data) /* sends data */

The HTTP request methods supported are:

GET
POST
HEAD

The object member variables:

.status /* holds teh status retured by ther server. e.g. 200,500,404 etc. */
.readyState /* the state of the operation e.g. 4=operation complete */
.responseText /* holds the text received from the request */
.responseXML /* in case the server returns XML this holds the XML data */

A simple example:

Code: JavaScript

var xmlhttp=false;
 try
 {
   xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); /* for IE < 5 */
 }
 catch (e)
 {
    try
    {
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    catch (E)
    {
    xmlhttp = false;
    }
 }
 
 /* mozilla & opera */
 if (!xmlhttp && typeof XMLHttpRequest!='undefined')
 {
   xmlhttp = new XMLHttpRequest();
 }
 
 xmlhttp.open("GET","mypage.php",true);
 xmlhttp.onreadystatechange=function()
 {
    if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
    {
       alert(xmlhttp.responseText);
    }
 }
 xmlhttp.send(null); /* are sending null because we dont have any data to post */

Hope this is helpful.


All times are GMT +5.5. The time now is 12:22.