You are on page 1of 12

XMLHttpRequest Object

Pgina 1 de 12

XMLHttpRequest Object
.NET Framework 3.0 Represents an XML request using HTTP. Members Table The following table lists the members exposed by the XMLHttpRequest object. Attributes/Properties Property constructor readyState
1 2

Description Returns a reference to the constructor of an object. Retrieves the current state of the request operation.

responseBody3 Retrieves the response body as an array of unsigned bytes.

4 responseText Retrieves the response body as a string. 5 Retrieves the response body as an XML Document Object Model responseXML (DOM) object.


6 7

Retrieves the HTTP status code of the request. Retrieves the friendly HTTP status of the request. Gets or sets the time-out value.

statusText timeout Events

Event Property


onreadystatechange Sets or retrieves the event handler for asynchronous requests. Raised when there is an error that prevents the completion of ontimeout10 the request. Methods Method abort
11 12

Description Cancels the current HTTP request. Registers an event handler for the specified event type. Sends an event to the current element.

addEventListener dispatchEvent

getAllResponseHeaders getResponseHeader open

16 15

Returns the complete list of response headers. Returns the specified response header. Assigns method, destination URL, and other optional attributes of a pending request. Removes an event handler that the addEventListener12 method registered. Sends an HTTP request to the server and receives a response. Adds custom HTTP headers to the request.

removeEventListener17 send

setRequestHeader19 Prototypes Object XMLHttpRequest 20 Constructor Remarks

Description Defines the properties and methods inherited by objects in 20 the XMLHttpRequest Constructor prototype chain.,v=vs.85).aspx


XMLHttpRequest Object

Pgina 2 de 12

The XMLHttpRequest property is available on the window



var oReq = new XMLHttpRequest;

With the XMLHttpRequest object, clients can retrieve and submit XML data directly to a web server without reloading the document. 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. The XMLHttpRequest property is available on the window object in Internet Explorer 7.

var oReq = new XMLHttpRequest;

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 9 uses an onreadystatechange 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 */) {,v=vs.85).aspx


XMLHttpRequest Object

Pgina 3 de 12

if (oReq.status == 200) { alert(oReq.responseText); } } } var oReq = getXMLHttpRequest(); if (oReq != null) {"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 22 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]-->,v=vs.85).aspx


XMLHttpRequest Object

Pgina 4 de 12

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

Standards Information This object is defined in The XMLHttpRequest Object (W3C Working Draft) .

Links Table
1 2 3 4 5 6 7 8 9

10 11 12 13 14 15 16 17 18 19 20 21 22 23

Community Content
Empty headers are ignored
Let me highlight the fact that adding just a header without specifying value is ignored by this class: after adding,v=vs.85).aspx


XMLHttpRequest Object

Pgina 5 de 12

MyRequest.setRequestHeader("SOAPAction", "") the SOAPAction header won't show up in the actual HTTP request going on the wire. Just saying... 8/24/2011 Erik Bitemo

Server.CreateObject("Microsoft.XMLHttp") gives an error Create XmlHttp Error=006~ASP 0177~Server.CreateObject Failed~800401f3

Here is actual code... Set xmlConn = Server.CreateObject("Microsoft.XMLHttp")

if err.number <> 0 then Response.Write "Create XmlHttp Error=" & err.Description Response.End end if

4/5/2011 Hrushi_phapale

Having Trouble
Greetings, I'm having trouble getting the following code to work in IE. It works in firefox without a problem. I think my problem is at the"GET", url, true); in the code below but not totally sure. I'm trying to get information from a form and update the information to the database. I'm able to get the information from the screen but the information is not getting the page which receiving the request and to the database. Any help would be appreciated. // JavaScript Document var geturl = "http://www." + window.location.hostname + "/demo"; function getMessageResponse() { var getdate = document.getElementById('fm_tt_date').value; var gettime = document.getElementById('fm_tt_time').value; if(getdate == "MM/DD/YY" || gettime == "HH:MM") {alert("Please fill out times, or click the set button.")} else {,v=vs.85).aspx


XMLHttpRequest Object

Pgina 6 de 12

var xmlHttp; try { // Internet Explorer xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { try { // Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); } catch (e) { try { xmlHttp= new ActiveXObject("MSXML2.XMLHTTP.3.0"); } catch (e) { alert("Your browser does not support AJAX!"); return false; } } } var var var var getdate = document.getElementById('fm_tt_date').value; gettime = document.getElementById('fm_tt_time').value; getprojid = document.getElementById('fm_project_idnum').value; getsubuser = document.getElementById('fm_create_user').value;

for (var i=0; i < document.psheetform.fm_tt_stend.length; i++) { if (document.psheetform.fm_tt_stend[i].checked) { var getstend = document.psheetform.fm_tt_stend[i].value; } } var url= geturl+"/content/process/recordtime.php"; url=url+"? getdate="+getdate+"&gettime="+gettime+"&getstend="+getstend+"&getprojid="+getprojid +"&getsubuser="+getsubuser; url=url+"&sid="+Math.random();"GET", url, true); xmlHttp.onreadystatechange=function() { if(xmlHttp.readyState==4) { if(document.psheetform.fm_tt_stend[0].checked) { document.psheetform.fm_tt_stend[0].checked=false; document.psheetform.fm_tt_stend[1].checked=true; } else {,v=vs.85).aspx


XMLHttpRequest Object

Pgina 7 de 12

document.psheetform.fm_tt_stend[0].checked=true; document.psheetform.fm_tt_stend[1].checked=false; } alert(getstend+" time of "+getdate+", "+gettime+" was recorded"); } } xmlHttp.send(); } } 11/23/2010 BirdsButterflies 11/4/2010 BirdsButterflies

Use Sync XMLHttpRequest in Async callback function will block the js Interpreter
insertTR("31935","IOA_Call","969|0","2010-10-15 19:45:00"); insertTR("31736","IOA_Call","968|0","2010-10-15 19:44:00"); insertTR("31546","IOA_Call","946|0","2010-10-15 10:16:00"); insertTR("31424","IOA_Call","945|0","2010-10-15 9:51:00"); insertTR("31279","IOA_Call","941|0","2010-10-15 9:15:00"); insertTR("31150","IOA_Call","935|0","2010-10-14 14:53:00"); insertTR("30840","IOA_Call","920|0","2010-10-14 9:11:00"); insertTR("30700","IOA_Call","919|0","2010-10-14 8:47:00"); insertTR("30642","IOA_Call","912|0","2010-10-13 15:46:00"); insertTR("30523","IOA_Call","903|0","2010-10-13 15:11:00"); insertTR("30308","IOA_Call","900|0","2010-10-13 15:01:00"); insertTR("30084","IOA_Call","899|0","2010-10-13 14:31:00"); insertTR("29861","IOA_Call","898|0","2010-10-13 14:30:00"); insertTR("29555","IOA_Task","1;2010-10-13 11:25:00,2010-10-13 11:25:00,101,5795","2010-10-13 11:25:00"); insertTR("29347","IOA_Call","875|0","2010-10-12 11:47:00"); function insertTR(Callid,CallType,CallContent,CallTime) { var X=new ActiveXObject("Microsoft.XMLHTTP") X.onreadystatechange=function() { if(X.readyState==4) { if(X.status==200) { var strR=X.responseText; if(strR!="") { noReadDiv.innerHTML=post_http("<div>xxx</div>"); } } } }'POST',"xxxURL",true); X.send("xxPostData"); } Refresh the IE8 several times,A runtime error occur in the line: noReadDiv.innerHTML=SF_func_post_http("<div>xxx</div>");. finally I get the reason,becase post_http is a sync xmlhttprequest use XMLHttpRequest() as,v=vs.85).aspx


XMLHttpRequest Object

Pgina 8 de 12

the constructor ,which is different from var X=new ActiveXObject("Microsoft.XMLHTTP") Can you please explain the reason,and tell a way to solve this?? Thanks!! 10/22/2010 ncuboy

In response to the "bug" wherein one request will wait for another to finish ... $0$0 $0 $0To the best of my knowledge, most web browsers only allow themselves up to 2 simultaneous connections to a given host. So, if you start 2 AJAX requests, any attempt to open a 3rd will get stuck waiting for one of the first 2 to complete. And if you have any images, scripts, or stylesheets in queue, your AJAX requests could be stuck waiting for those as well.$0 $0$0 $0 $0But again, this only applies if these requests are all coming from the same server. And I'm not 100% sure whether the determining factor there is IP address or hostname. In any case, this could be the "bug" you're seeing.$0 9/3/2010 Svidgen

xmlHttpRequest Bug
I have been trying to solve a problem with the asynchronous xmlhttprequest call. I call a Perl program that will sleep for a random number of seconds (0-15) and return the number of seconds that the perl program slept. I am using the request to call the program 3 times. The onreadystatechange function updates 3 separate DIVS on the webpage with the time that the readystate changed. Sometimes, not every time, one call will wait (readystate=3) for another call to finish. Code example: function g() { for (var i=0; i<3; i++) { getResults(i) } } function getResults(divId) { var x = new XMLHttpRequest();"GET",<URL>,true); x.onreadystatechange = function() { var now = new Date(); document.getElementById('div' + divId).innerHTML += x.readyState + ": " + now.toLocaleTimeString() + "<br>"; if (x.readyState == 4) { document.getElementById('div' + divId).innerHTML += 'Slept for ' + x.responseText + ' seconds'; } },v=vs.85).aspx


XMLHttpRequest Object

Pgina 9 de 12

x.send() } 2/11/2010 griff415 2/11/2010 griff415

If you send a XMLHttpRequest to the server using the GET method, and the server responds with an emply text (Content-Length=0), IE7 and IE8 send the request again, so you will see two calls instead of one, on your server's log. Normaly you don't want to respond with a zero length page, however in some cases such as an invalid parameter or other kind of error you may want to notifiy the JScript about the error without having to send a whole bunch of useless text. No other web browser behaves like this, so it must be a bug. This does not happen is you use the POST method. 12/8/2009 george_5154

bad code sample

if (window.XMLHttpRequest) { var oReq = new XMLHttpRequest();"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. 10/9/2009 John Sudds 3/30/2009 yecril

Whatever happened to Microsoft.XMLHTTP?

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. 8/18/2009 John Sudds 8/18/2009 John Sudds

Ajax -- Onreadystatechange method is not called,v=vs.85).aspx


XMLHttpRequest Object

Pgina 10 de 12

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 {"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;"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 :,v=vs.85).aspx


XMLHttpRequest Object

Pgina 11 de 12

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.

8/18/2009 John Sudds

5/13/2008 Bhoomi1

A BASIC version

A couple of Hints
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.,v=vs.85).aspx


XMLHttpRequest Object

Pgina 12 de 12

10/1/2008 dpminusa

NTLM Authentication & Load Balancing

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. 6/23/2008 Tom At Moto

2011 Microsoft. All rights reserved.,v=vs.85).aspx