Click to Rate and Give Feedback
MSDN
MSDN Library
Web Development
HTML and CSS
Objects
 XMLHttpRequest Object
XMLHttpRequest Object

Represents an XML request usingHTTP.

Members Table

The following table lists the members exposed by the XMLHttpRequest object.

Attributes/Properties
Show:
PropertyDescription
constructor New for Windows Internet Explorer 8  Returns a reference to the constructor of an object.
readyState Retrieves the current state of the request operation.
responseBody Retrieves the response body as an array of unsigned bytes.
responseText Retrieves the response body as a string.
responseXML Retrieves the response body as an XML Document Object Model (DOM) object.
status Retrieves the HTTP status code of the request.
statusText Retrieves the friendly HTTP status of the request.
timeout New for Internet Explorer 8  Gets or sets the time-out value.
EventDescription
onreadystatechange Sets or retrieves the event handler for asynchronous requests.
ontimeout New for Internet Explorer 8  Raised when there is an error that prevents the completion of the request.
MethodDescription
abort Cancels the current HTTP request.
getAllResponseHeaders Returns the complete list of response headers.
getResponseHeader Returns the specified response header.
open Assigns method, destination URL, and other optional attributes of a pending request.
send Sends an HTTP request to the server and receives a response.
setRequestHeader Adds custom HTTP headers to the request.
ObjectDescription
XMLHttpRequest Constructor New for Internet Explorer 8  Defines the properties and methods inherited by objects in the XMLHttpRequest Constructor prototype chain.

Remarks

The XMLHttpRequest property is available on the window object in Internet Explorer 7.

var oReq = new XMLHttpRequest;

With the XMLHttpRequest object, Internet Explorer clients can retrieve and submit XML data directly to a Web server without reloading the page. To convert XML data into renderable HTML content, use the client-side XML DOM or Extensible Stylesheet Language Transformations (XSLT) to compose HTML elements for presentation.

The native scripting object also supports the use of expandos (custom properties), and properly recognizes the 'this' notation of JavaScript.

To support versions of Internet Explorer prior to Internet Explorer 7, use the following function to get the XMLHttpRequest object:

function getXMLHttpRequest() 
{
    if (window.XMLHttpRequest) {
        return new window.XMLHttpRequest;
    }
    else {
        try {
            return new ActiveXObject("MSXML2.XMLHTTP.3.0");
        }
        catch(ex) {
            return null;
        }
    }
}

Examples

The following script demonstrates how to create and use the XMLHttpRequest object. For best client-side performance, the XMLHTTP request is asynchronous and uses anonreadystatechange event handler to process the data returned by the call. The script uses the getXMLHttpRequest() function defined above to create the request object.

function handler()
{
    if (oReq.readyState == 4 /* complete */) {
        if (oReq.status == 200) {
            alert(oReq.responseText);
        }
    }
}

var oReq = getXMLHttpRequest();

if (oReq != null) {
    oReq.open("GET", "http://localhost/test.xml", true);
    oReq.onreadystatechange = handler;
    oReq.send();
}
else {
    window.alert("AJAX (XMLHTTP) not supported.");
}

The following example demonstrates the same functionality in Microsoft Visual Basic Scripting Edition (VBScript).

<script type="text/vbscript">
Dim objXML
Function objXML_onreadystatechange()
    If (objXML.readyState = 4) Then
        If (objXML.status = 200) Then
            MsgBox objXML.responseText, 0, objXML.statusText
        End If
    End If
End Function

Function Window_onload()
    If IsObject(window.XmlHttpRequest) Then
        objXML = window.XmlHttpRequest
    Else
        Set objXML = CreateObject("MSXML2.XMLHTTP.3.0")
    End If

    objXML.Open "GET", "http://localhost/test.xml", True
    objXML.OnReadyStateChange = GetRef("objXML_onreadystatechange")
    objXML.Send
End Function
</script> 

In Internet Explorer 8, the VBScript syntax is not supported, which complicates native support detection somewhat. One way to detect Internet Explorer 8 is by using conditional comments. The following comment detects Internet Explorer 8 when it is not running in compatibility mode. The script sets a global variable that can be checked later when creating the XMLHttpRequest object.

<!--[if IE 8]><script type="text/vbscript">
vbIE8 = True
</script><![endif]-->

If Not vbIE8 And IsObject(window.XmlHttpRequest) Then ...
  

Standards Information

This object is defined in The XMLHttpRequest Object (W3C Working Draft) World Wide Web link.

Tags What's this?: ajax (x) Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Ajax -- Onreadystatechange method is not called      Bhoomi ... John Sudds   |   Edit   |   Show History
Hi:

I am facing a problem in ajax.

My code functionality is retrieving data from database. For it i am using ajax.

i am including the code below which contains ajax function:

<script>
var req;
var which;

function fetchCorpClassTaxonomy(url) {
alert("entered into Ajax function");
if (window.XMLHttpRequest) { // Non-IE browsers
alert("NON IE Block is Invoked");
req = new XMLHttpRequest();
req.onreadystatechange = processStateChange;
try {
req.open("GET", url, true);
} catch (e) {
alert(e);
}
req.send(null);

} else if (window.ActiveXObject) { // IE
alert("entered into IE block");
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req) {
alert("entered into if(req)");
req.onreadystatechange = processStateChange;
req.open("GET", url, true);
alert("readystate: "+ req.readyState);
req.send();
}
}
}

function processStateChange() {
alert("entered into processStateChange()");
if (req.readyState == 4) { // Complete
if (req.status == 200) { // OK response
... STUFF REMOVED ...;
}
} else {
alert("Problem: " + req.statusText);
}
}
}
</script>

I am getting response from action class so there is no problem in my other code.

when fetchCorpClassTaxonomy(url) function is called it is going to IE block since i am using IE 7.0

After that
alert("readystate: "+ req.readyState);
is also coming.

but the function processStateChange() is not called.
The alert just inside the function :

alert("entered into processStateChange()"); is also not executing.


The problem is function processStateChange() is not called.


Please give me your valuable suggestions As Soon As Possible for solving the problem. Since i am new to Ajax I am not able to find the solution.

Thanks.....


[[jsudds.MSFT]] On IE, XMLHttpRequest object properties are reset when you call the open method. The onreadystatechange handler you just set on the line above is thrown away. Just switch the order of those two lines.

TO RECAP: Calling the open method initializes the request object. If you have set properties (such as onreadystatechange) it is reset to initial default values (NULL). So, do all your initialization between OPEN and the final call to SEND.

Tags What's this?: Add a tag
Flag as ContentBug
NTLM Authentication & Load Balancing      Tom At Moto   |   Edit   |   Show History
It seems that there's also an issue with load balancing (using the IIS load balancer) and NTLM authentication on IE. Basically, you either get prompted to log in, or nothing happens at all (and an error is thrown: "The download of the specified resource has failed."

I've also seen this happen when using AJAX resources through a router or firewall that requires NTLM authentication.
Tags What's this?: Add a tag
Flag as ContentBug
A couple of Hints      dpminusa   |   Edit   |   Show History

Two things that may be obvious but that are overlooked. May be helpful.

  1. POST works properly with multiple requessts to the same object. GET does not. So try POST when you experience problems.
  2. Returning values from a function that uses a request object may result in the caller proceeding before the callee is ready to return a value. For correct operation the callee needs a loop or event to delay/synchronize to the callee completion.
Tags What's this?: Add a tag
Flag as ContentBug
bad code sample      yecril ... John Sudds   |   Edit   |   Show History
if (window.XMLHttpRequest)
{
   var oReq = new XMLHttpRequest();
   oReq.open("GET", "http://localhost/test.xml");
   oReq.send();
   alert(oReq.statusText); // fails
}

The request is asynchronous, it will run only after the calling current script completes.


[[jsudds.MSFT]] Thanks for reporting! The code samples in the article above have been updated, but I'm leaving your example here in the event that it might help someone to see why their code is not working as expected.

Tags What's this?: dhtml (x) Add a tag
Flag as ContentBug
A BASIC version      yecril   |   Edit   |   Show History
CLASS T3REQ4CALL4BACK
DIM M3REQ
PUBLIC DEFAULT PROPERTY GET HANDLER
IF M3REQ. READYSTATE = &O4 THEN MSGBOX M3REQ. STATUSTEXT,, "STATUS"
END PROPERTY
END CLASS

SET A3REQ = WINDOW. XMLHTTPREQUEST. CREATE
A3REQ. OPEN "HEAD", "http://msdn.microsoft.com/"
A3REQ. SEND
SET A4CALL4BACK = NEW T3REQ4CALL4BACK
SET A4CALL4BACK. M3REQ = A3REQ
A3REQ. ONREADYSTATECHANGE = A4CALL4BACK
REM AMAZINGLY, "SET" IS NOT NEEDED AND FAILS HERE
REM REMINDER: DO NOT WAIT FOR THE REPLY HERE, 
REM IT WILL NOT ARRIVE AS LONG AS YOUR SCRIPT IS BUSY!
Whatever happened to Microsoft.XMLHTTP?      John Sudds   |   Edit   |   Show History
Getting the right ProgID for XMLHTTP is important. It turns out that there are only two real options, and you should know the difference between them. Check out the blog post on this subject at the Microsoft XML Team's WebLog.

http://blogs.msdn.com/xmlteam/archive/2006/10/23/using-the-right-version-of-msxml-in-internet-explorer.aspx
Processing
© 2009 Microsoft Corporation. All rights reserved. Terms of Use | Trademarks | Privacy Statement | Site Feedback
Page view tracker