XMLHttpRequest object
[This documentation is preliminary and is subject to change.]
Represents an XML request using HTTP.
Standards information
- XMLHttpRequest, Section 3
Remarks
The XMLHttpRequest property is available on the window object.
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 Document Object Model (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 Windows Internet Explorer 7.
var oReq = new XMLHttpRequest;
To support versions of Windows 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 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 */) {
if (oReq.status == 200) {
console.log(oReq.responseText);
}
}
}
var oReq = getXMLHttpRequest();
if (oReq != null) {
oReq.open("GET", "http://localhost/test.xml", true);
oReq.onreadystatechange = handler;
oReq.send();
}
else {
window.console.log("AJAX (XMLHTTP) not supported.");
}
The following example demonstrates the same functionality in 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 ...
Build date: 2/14/2012
- 4/5/2011
- Hrushi_phapale
- 4/7/2012
- David Bowen
I have accidentally found out that in some version of IE6, it doesn't support onreadystatechange property. Please advise if there is any workaround for this. Although I have used the code provided above, it doesn't seems to solve the issue.
function getXMLHttpRequest() {
if (window.XMLHttpRequest) {
return new window.XMLHttpRequest;
}
else {
try {
return new ActiveXObject("MSXML2.XMLHTTP.3.0");
}
catch (ex) {
return null;
}
}
}
- 11/2/2011
- Maryanto
Let me highlight the fact that adding just a header without specifying value is ignored by this class: after adding
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
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 xmlHttp.open("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
{
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 getdate = document.getElementById('fm_tt_date').value;
var gettime = document.getElementById('fm_tt_time').value;
var getprojid = document.getElementById('fm_project_idnum').value;
var 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();
xmlHttp.open("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
{
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/4/2010
- BirdsButterflies
- 11/23/2010
- BirdsButterflies
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>");
}
}
}
}
X.open('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 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
- 9/3/2010
- Svidgen
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();
x.open("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';
}
}
x.send()
}
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
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.
- 3/30/2009
- yecril
- 10/9/2009
- John Sudds [Microsoft]
http://blogs.msdn.com/xmlteam/archive/2006/10/23/using-the-right-version-of-msxml-in-internet-explorer.aspx
- 8/18/2009
- John Sudds [Microsoft]
- 8/18/2009
- John Sudds [Microsoft]
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:
I am getting response from action class so there is no problem in my other code.<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>
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.
- 5/13/2008
- Bhoomi
- 8/18/2009
- John Sudds [Microsoft]
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!
Two things that may be obvious but that are overlooked. May be helpful.
- POST works properly with multiple requessts to the same object. GET does not. So try POST when you experience problems.
- 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.
- 10/1/2008
- dpminusa
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