Cookies improve the way our website works, by using this website you are agreeing to our use of cookies. For more information see our privacy policy.
OK
First initialize an XMLHttpRequest object with the open method, then specify the necessary request headers with the setRequestHeader method and finally send the request with the send method.
Syntax:
object.open(method, URL [, async [, user [, password]]]);
Required. String that specifies the HTTP method (GET, POST, DELETE, HEAD, OPTIONS, PUT) to use. This parameter is case-insensitive.
URL
Required. String that specifies the URL where the request needs to be sent. The specified URL must be in the same domain as the current document.
async
Optional. Boolean that specifies whether the request needs to be handled asynchronously or not.
One of the following values:
false
While the operation is in progress the send method does not return. Do not use this value if you do not want to keep the user waiting.
true
The send method returns immediately. Use the onreadystatechange event to be notified about the states of the request.
user
Optional. String that specifies the name of the user for authentication. Default is an empty string.
password
Optional. String that specifies the password of the user for authentication. Default is an empty string.
Return value:
This method has no return value.
Example HTML code 1:
This example illustrates the use of the an external XML file to insert data into a table:
Code
ajax.js
news.xml
<head><scripttype="text/javascript"src="ajax.js"></script><scripttype="text/javascript">var httpRequest = null;
function SendRequest () {
if (!httpRequest) {
httpRequest = CreateHTTPRequestObject (); // defined in ajax.js
}
if (httpRequest) {
// The requested file must be in the same domain that the page is served from.
var url = "news.xml";
httpRequest.open ("GET", url, true); // async
httpRequest.onreadystatechange = OnStateChange;
httpRequest.send (null);
}
}
function OnStateChange () {
if (httpRequest.readyState == 0 || httpRequest.readyState == 4) {
if (IsRequestSuccessful (httpRequest)) { // defined in ajax.js
FillTable ();
}
else {
alert ("Operation failed.");
}
}
}
function FillTable () {
var xmlDoc = ParseHTTPResponse (httpRequest); // defined in ajax.js
if (!xmlDoc)
return;
var resTable = document.getElementById ("resTable");
var xmlNodes = ["title", "description", "pubDate", "link"];
var itemTags = xmlDoc.getElementsByTagName ("item");
for (i = 0; i < itemTags.length; i++) {
resTable.insertRow (i);
for (j = 0; j < xmlNodes.length; j++) {
var recordNode = itemTags[i].getElementsByTagName (xmlNodes[j])[0];
resTable.rows[i].insertCell (j);
if ('textContent'in recordNode)
resTable.rows[i].cells[j].innerHTML = recordNode.textContent;
else
resTable.rows[i].cells[j].innerHTML = recordNode.text;
}
}
}
</script></head><bodyonload="SendRequest ()"><tableborder="1px"><theadstyle="font-weight: bold;"><tr><td>Title</td><td>Description</td><td>PubDate</td><td>Link</td></tr></thead><tbodyid="resTable"></tbody></table></body>
function CreateHTTPRequestObject () {
// although IE supports the XMLHttpRequest object, but it does not work on local files.
var forceActiveX = (window.ActiveXObject && location.protocol === "file:");
if (window.XMLHttpRequest && !forceActiveX) {
returnnewXMLHttpRequest();
}
else {
try {
returnnewActiveXObject("Microsoft.XMLHTTP");
} catch(e) {}
}
alert ("Your browser doesn't support XML handling!");
returnnull;
}
function CreateMSXMLDocumentObject () {
if (typeof (ActiveXObject) != "undefined") {
var progIDs = [
"Msxml2.DOMDocument.6.0",
"Msxml2.DOMDocument.5.0",
"Msxml2.DOMDocument.4.0",
"Msxml2.DOMDocument.3.0",
"MSXML2.DOMDocument",
"MSXML.DOMDocument"
];
for (var i = 0; i < progIDs.length; i++) {
try {
returnnewActiveXObject(progIDs[i]);
} catch(e) {};
}
}
returnnull;
}
function CreateXMLDocumentObject (rootName) {
if (!rootName) {
rootName = "";
}
var xmlDoc = CreateMSXMLDocumentObject ();
if (xmlDoc) {
if (rootName) {
var rootNode = xmlDoc.createElement (rootName);
xmlDoc.appendChild (rootNode);
}
}
else {
if (document.implementation.createDocument) {
xmlDoc = document.implementation.createDocument ("", rootName, null);
}
}
return xmlDoc;
}
function ParseHTTPResponse (httpRequest) {
var xmlDoc = httpRequest.responseXML;
// if responseXML is not valid, try to create the XML document from the responseText property
if (!xmlDoc || !xmlDoc.documentElement) {
if (window.DOMParser) {
var parser = newDOMParser();
try {
xmlDoc = parser.parseFromString (httpRequest.responseText, "text/xml");
} catch (e) {
alert ("XML parsing error");
returnnull;
};
}
else {
xmlDoc = CreateMSXMLDocumentObject ();
if (!xmlDoc) {
returnnull;
}
xmlDoc.loadXML (httpRequest.responseText);
}
}
// if there was an error while parsing the XML document
var errorMsg = null;
if (xmlDoc.parseError && xmlDoc.parseError.errorCode != 0) {
errorMsg = "XML Parsing Error: " + xmlDoc.parseError.reason
+ " at line " + xmlDoc.parseError.line
+ " at position " + xmlDoc.parseError.linepos;
}
else {
if (xmlDoc.documentElement) {
if (xmlDoc.documentElement.nodeName == "parsererror") {
errorMsg = xmlDoc.documentElement.childNodes[0].nodeValue;
}
}
}
if (errorMsg) {
alert (errorMsg);
returnnull;
}
// ok, the XML document is valid
return xmlDoc;
}
// returns whether the HTTP request was successful
function IsRequestSuccessful (httpRequest) {
// IE: sometimes 1223 instead of 204
var success = (httpRequest.status == 0 ||
(httpRequest.status >= 200 && httpRequest.status < 300) ||
httpRequest.status == 304 || httpRequest.status == 1223);
return success;
}
<?xmlversion="1.0"encoding="utf-8"?><news><channel><item><title>Paula Abdul leaves American Idol</title><description>Paula Abdul has officially confirmed that she won’t be returning to American Idol this season. "With sadness in my heart, I’ve decided not to return to Idol," she wrote on her Twitter page.</description><pubDate>Wed, August 5, 2009 19:52:31 +0200</pubDate><link>http://www.tribute.ca/news/index.php/its-official-paula-abdul-leaves-american-idol/2009/08/05/</link></item><item><title>Criminal Minds star Moore hit by car</title><description>Shemar Moore, 39, who plays FBI Agent Derek Morgan in the CBS drama Criminal Minds, was hit by a car while bicycling in Los Angeles last Saturday.</description><pubDate>Thu, August 4, 2009 13:28:12 +0200</pubDate><link>http://www.tribute.ca/news/index.php/criminal-minds-star-moore-hit-by-car/2009/08/04/</link></item><item><title>Madonna writes love song for ex-husband</title><description>Madonna has sparked speculation that she wants to get back with her ex-husband, Guy Ritchie, after writing a love song for him in which she calls him her "eternal love".</description><pubDate>Fri, July 31, 2009 04:01:50 +0200</pubDate><link>http://www.tribute.ca/news/index.php/madonna-writes-love-song-for-ex-husband/2009/07/31/</link></item></channel></news>
This example is the same as the previous, but it demonstrates a synchronous operation:
Code
ajax.js
news.xml
<head><scripttype="text/javascript"src="ajax.js"></script><scripttype="text/javascript">var httpRequest = null;
function SendRequest () {
if (!httpRequest) {
httpRequest = CreateHTTPRequestObject (); // defined in ajax.js
}
if (httpRequest) {
// The requested file must be in the same domain that the page is served from.
var url = "news.xml";
httpRequest.open ("GET", url, false); // synchron
httpRequest.send (null);
FillTable ();
}
}
function FillTable () {
var xmlDoc = ParseHTTPResponse (httpRequest); // defined in ajax.js
if (!xmlDoc)
return;
var resTable = document.getElementById ("resTable");
var xmlNodes = ["title", "description", "pubDate", "link"];
var itemTags = xmlDoc.getElementsByTagName ("item");
for (i = 0; i < itemTags.length; i++) {
resTable.insertRow (i);
for (j = 0; j < xmlNodes.length; j++) {
var recordNode = itemTags[i].getElementsByTagName (xmlNodes[j])[0];
resTable.rows[i].insertCell (j);
if ('textContent'in recordNode)
resTable.rows[i].cells[j].innerHTML = recordNode.textContent;
else
resTable.rows[i].cells[j].innerHTML = recordNode.text;
}
}
}
</script></head><bodyonload="SendRequest ()"><tableborder="1px"><theadstyle="font-weight: bold;"><tr><td>Title</td><td>Description</td><td>PubDate</td><td>Link</td></tr></thead><tbodyid="resTable"></tbody></table></body>
function CreateHTTPRequestObject () {
// although IE supports the XMLHttpRequest object, but it does not work on local files.
var forceActiveX = (window.ActiveXObject && location.protocol === "file:");
if (window.XMLHttpRequest && !forceActiveX) {
returnnewXMLHttpRequest();
}
else {
try {
returnnewActiveXObject("Microsoft.XMLHTTP");
} catch(e) {}
}
alert ("Your browser doesn't support XML handling!");
returnnull;
}
function CreateMSXMLDocumentObject () {
if (typeof (ActiveXObject) != "undefined") {
var progIDs = [
"Msxml2.DOMDocument.6.0",
"Msxml2.DOMDocument.5.0",
"Msxml2.DOMDocument.4.0",
"Msxml2.DOMDocument.3.0",
"MSXML2.DOMDocument",
"MSXML.DOMDocument"
];
for (var i = 0; i < progIDs.length; i++) {
try {
returnnewActiveXObject(progIDs[i]);
} catch(e) {};
}
}
returnnull;
}
function CreateXMLDocumentObject (rootName) {
if (!rootName) {
rootName = "";
}
var xmlDoc = CreateMSXMLDocumentObject ();
if (xmlDoc) {
if (rootName) {
var rootNode = xmlDoc.createElement (rootName);
xmlDoc.appendChild (rootNode);
}
}
else {
if (document.implementation.createDocument) {
xmlDoc = document.implementation.createDocument ("", rootName, null);
}
}
return xmlDoc;
}
function ParseHTTPResponse (httpRequest) {
var xmlDoc = httpRequest.responseXML;
// if responseXML is not valid, try to create the XML document from the responseText property
if (!xmlDoc || !xmlDoc.documentElement) {
if (window.DOMParser) {
var parser = newDOMParser();
try {
xmlDoc = parser.parseFromString (httpRequest.responseText, "text/xml");
} catch (e) {
alert ("XML parsing error");
returnnull;
};
}
else {
xmlDoc = CreateMSXMLDocumentObject ();
if (!xmlDoc) {
returnnull;
}
xmlDoc.loadXML (httpRequest.responseText);
}
}
// if there was an error while parsing the XML document
var errorMsg = null;
if (xmlDoc.parseError && xmlDoc.parseError.errorCode != 0) {
errorMsg = "XML Parsing Error: " + xmlDoc.parseError.reason
+ " at line " + xmlDoc.parseError.line
+ " at position " + xmlDoc.parseError.linepos;
}
else {
if (xmlDoc.documentElement) {
if (xmlDoc.documentElement.nodeName == "parsererror") {
errorMsg = xmlDoc.documentElement.childNodes[0].nodeValue;
}
}
}
if (errorMsg) {
alert (errorMsg);
returnnull;
}
// ok, the XML document is valid
return xmlDoc;
}
// returns whether the HTTP request was successful
function IsRequestSuccessful (httpRequest) {
// IE: sometimes 1223 instead of 204
var success = (httpRequest.status == 0 ||
(httpRequest.status >= 200 && httpRequest.status < 300) ||
httpRequest.status == 304 || httpRequest.status == 1223);
return success;
}
<?xmlversion="1.0"encoding="utf-8"?><news><channel><item><title>Paula Abdul leaves American Idol</title><description>Paula Abdul has officially confirmed that she won’t be returning to American Idol this season. "With sadness in my heart, I’ve decided not to return to Idol," she wrote on her Twitter page.</description><pubDate>Wed, August 5, 2009 19:52:31 +0200</pubDate><link>http://www.tribute.ca/news/index.php/its-official-paula-abdul-leaves-american-idol/2009/08/05/</link></item><item><title>Criminal Minds star Moore hit by car</title><description>Shemar Moore, 39, who plays FBI Agent Derek Morgan in the CBS drama Criminal Minds, was hit by a car while bicycling in Los Angeles last Saturday.</description><pubDate>Thu, August 4, 2009 13:28:12 +0200</pubDate><link>http://www.tribute.ca/news/index.php/criminal-minds-star-moore-hit-by-car/2009/08/04/</link></item><item><title>Madonna writes love song for ex-husband</title><description>Madonna has sparked speculation that she wants to get back with her ex-husband, Guy Ritchie, after writing a love song for him in which she calls him her "eternal love".</description><pubDate>Fri, July 31, 2009 04:01:50 +0200</pubDate><link>http://www.tribute.ca/news/index.php/madonna-writes-love-song-for-ex-husband/2009/07/31/</link></item></channel></news>
This example and the next one use AJAX to submit a form without reloading the page. The two examples are similar, but the first one uses synchronous while the second one uses asynchronous data transfer. In synchronous mode, the send method of the XMLHttpRequest object waits for a reply, so the user cannot interact with the browser until the response has completed. In asynchronous mode, the send method does not wait for a reply but instead returns immediately, so it allows you to perform other operations while a time-consuming task is being performed in the background.
Code
ajax_form.js
register.php
<head><scripttype="text/javascript"src="ajax_form.js"></script><style>.error {
display: none;
color: #a00000;
font-weight: bold;
}
</style><scripttype="text/javascript">function HideAllErrorFields () {
for (var i = 1; i <= 4; i++) {
var field = document.getElementById ("error" + i);
field.style.display = "none";
}
}
function ShowErrorFields (idsStr) {
var ids = idsStr.split (",");
for (var i = 0; i < ids.length; i++) {
var field = document.getElementById ("error" + ids[i]);
if (field) {
field.style.display = "block";
}
}
}
function AjaxSend (form, url, method) {
// hide all error fields
HideAllErrorFields ();
// get message data
var data = GetMessageBody (form); // defined in ajax_form.js
// send the request
var httpRequest = CreateRequestObj (); // defined in ajax_form.js
// try..catch is required if working offline
try {
httpRequest.open (method, url, false); // synchron
httpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
httpRequest.send (data);
}
catch (e) {
alert ("Cannot connect to the server!");
return;
}
// handle the response
if (IsRequestSuccessful (httpRequest)) { // defined in ajax_form.js
if (httpRequest.responseText === "ok") { // registration is successful
alert ("Thank you for registering");
/*
// if redirection is required
location.href = "/index.php";
*/
}
else { // some fields are invalid
ShowErrorFields (httpRequest.responseText);
}
}
else {
alert ("An error occurred while registering. Please try it again.");
}
}
</script></head><body>
This is a sample registration form.
The username must be between 2 and 20 characters, the password must be between 6 and 20 characters.
A user named Dottoro is already registered.
<br/>
Try to register both valid and invalid values!
<br/><br/><formonsubmit="AjaxSend (this, 'register.php', 'post'); return false;">
User Name: <inputtype="text"name="userName"/><divclass="error"id="error1">Must be between 2 and 20 characters.</div><divclass="error"id="error2">A user already exists with the same name.</div><br/><br/>
Password: <inputtype="password"name="password"/><divclass="error"id="error3">Must be between 6 and 20 characters.</div><br/><br/>
Repeat Password: <inputtype="password"name="repassword"/><divclass="error"id="error4">Must be the same as the password.</div><br/><br/><inputtype="submit"value="Register"/></form></body>
function CreateRequestObj () {
// although IE supports the XMLHttpRequest object, but it does not work on local files.
var forceActiveX = (window.ActiveXObject && location.protocol === "file:");
if (window.XMLHttpRequest && !forceActiveX) {
returnnewXMLHttpRequest();
}
else {
try {
returnnewActiveXObject("Microsoft.XMLHTTP");
} catch(e) {}
}
}
// create HTTP request body form form data
function GetMessageBody (form) {
var data = "";
for (var i = 0; i < form.elements.length; i++) {
var elem = form.elements[i];
if (elem.name) {
var nodeName = elem.nodeName.toLowerCase ();
var type = elem.type ? elem.type.toLowerCase () : "";
// if an input:checked or input:radio is not checked, skip it
if (nodeName === "input" && (type === "checkbox" || type === "radio")) {
if (!elem.checked) {
continue;
}
}
var param = "";
// select element is special, if no value is specified the text must be sent
if (nodeName === "select") {
for (var j = 0; j < elem.options.length; j++) {
var option = elem.options[j];
if (option.selected) {
var valueAttr = option.getAttributeNode ("value");
var value = (valueAttr && valueAttr.specified) ? option.value : option.text;
if (param != "") {
param += "&";
}
param += encodeURIComponent (elem.name) + "=" + encodeURIComponent (value);
}
}
}
else {
param = encodeURIComponent (elem.name) + "=" + encodeURIComponent (elem.value);
}
if (data != "") {
data += "&";
}
data += param;
}
}
return data;
}
// returns whether the HTTP request was successful
function IsRequestSuccessful (httpRequest) {
// IE: sometimes 1223 instead of 204
var success = (httpRequest.status == 0 ||
(httpRequest.status >= 200 && httpRequest.status < 300) ||
httpRequest.status == 304 || httpRequest.status == 1223);
return success;
}
This example is similar to the previous one, but it uses asynchronous data transfer and displays blinking text while waiting for the server response (the register_delay.php script waits two seconds before responding).
Code
ajax_form.js
register_delay.php
<head><scripttype="text/javascript"src="ajax_form.js"></script><style>.error {
display: none;
color: #a00000;
font-weight: bold;
}
#progress {
visibility: hidden;
color: #00a000;
}
</style><scripttype="text/javascript">function HideAllErrorFields () {
for (var i = 1; i <= 4; i++) {
var field = document.getElementById ("error" + i);
field.style.display = "none";
}
}
function ShowErrorFields (idsStr) {
var ids = idsStr.split (",");
for (var i = 0; i < ids.length; i++) {
var field = document.getElementById ("error" + ids[i]);
if (field) {
field.style.display = "block";
}
}
}
var registering = false;
function OnReadyStateChanged (httpRequest, form) {
if (httpRequest.readyState == 0 || httpRequest.readyState == 4) {
registering = false;
StopAnim ();
// prevent memory leaks
httpRequest.onreadystatechange = null;
if (IsRequestSuccessful (httpRequest)) { // defined in ajax_form.js
if (httpRequest.responseText === "ok") { // registration is successful
alert ("Thank you for registering");
/*
// if redirection is required
location.href = "/index.php";
*/
}
else { // some fields are invalid
ShowErrorFields (httpRequest.responseText);
}
}
else {
alert ("An error occurred while registering. Please try it again.");
}
}
}
function AjaxSend (form, url, method) {
// avoid resend data while registering
if (registering) {
return;
}
// hide all error fields
HideAllErrorFields ();
// get message data
var data = GetMessageBody (form); // defined in ajax_form.js
// send the request
var httpRequest = CreateRequestObj (); // defined in ajax_form.js
// try..catch is required if working offline
try {
httpRequest.open (method, url, true); // asynchron
httpRequest.onreadystatechange = function () {OnReadyStateChanged (httpRequest, form)};
httpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
httpRequest.send (data);
}
catch (e) {
alert ("Cannot connect to the server!");
return;
}
registering = true;
StartAnim ();
}
// blinking text
var animTimerId = 0;
function StartAnim () {
var progress = document.getElementById ("progress");
progress.style.visibility = "visible";
animTimerId = setInterval (RegAnim, 100);
}
function RegAnim () {
var progress = document.getElementById ("progress");
progress.style.visibility = (progress.style.visibility == "visible") ? "hidden" : "visible";
}
function StopAnim () {
var progress = document.getElementById ("progress");
progress.style.visibility = "hidden";
clearInterval (animTimerId);
}
</script></head><body>
This is a sample registration form.
The username must be between 2 and 20 characters, the password must be between 6 and 20 characters.
A user named Dottoro is already registered.
<br/>
Try to register both valid and invalid values!
<br/><br/><formonsubmit="AjaxSend (this, 'register_delay.php', 'post'); return false;">
User Name: <inputtype="text"name="userName"/><divclass="error"id="error1">Must be between 2 and 20 characters.</div><divclass="error"id="error2">A user already exists with the same name.</div><br/><br/>
Password: <inputtype="password"name="password"/><divclass="error"id="error3">Must be between 6 and 20 characters.</div><br/><br/>
Repeat Password: <inputtype="password"name="repassword"/><divclass="error"id="error4">Must be the same as the password.</div><br/><br/><inputtype="submit"value="Register"/><divid="progress">Registering</div></form></body>
function CreateRequestObj () {
// although IE supports the XMLHttpRequest object, but it does not work on local files.
var forceActiveX = (window.ActiveXObject && location.protocol === "file:");
if (window.XMLHttpRequest && !forceActiveX) {
returnnewXMLHttpRequest();
}
else {
try {
returnnewActiveXObject("Microsoft.XMLHTTP");
} catch(e) {}
}
}
// create HTTP request body form form data
function GetMessageBody (form) {
var data = "";
for (var i = 0; i < form.elements.length; i++) {
var elem = form.elements[i];
if (elem.name) {
var nodeName = elem.nodeName.toLowerCase ();
var type = elem.type ? elem.type.toLowerCase () : "";
// if an input:checked or input:radio is not checked, skip it
if (nodeName === "input" && (type === "checkbox" || type === "radio")) {
if (!elem.checked) {
continue;
}
}
var param = "";
// select element is special, if no value is specified the text must be sent
if (nodeName === "select") {
for (var j = 0; j < elem.options.length; j++) {
var option = elem.options[j];
if (option.selected) {
var valueAttr = option.getAttributeNode ("value");
var value = (valueAttr && valueAttr.specified) ? option.value : option.text;
if (param != "") {
param += "&";
}
param += encodeURIComponent (elem.name) + "=" + encodeURIComponent (value);
}
}
}
else {
param = encodeURIComponent (elem.name) + "=" + encodeURIComponent (elem.value);
}
if (data != "") {
data += "&";
}
data += param;
}
}
return data;
}
// returns whether the HTTP request was successful
function IsRequestSuccessful (httpRequest) {
// IE: sometimes 1223 instead of 204
var success = (httpRequest.status == 0 ||
(httpRequest.status >= 200 && httpRequest.status < 300) ||
httpRequest.status == 304 || httpRequest.status == 1223);
return success;
}