DOM XMLHttpRequest
The XMLHttpRequest Object
The XMLHttpRequest object allows you to update a portion of a web page without reloading the entire page.
XMLHttpRequest Object
The XMLHttpRequest object is used behind the scenes to exchange data with the server.
The XMLHttpRequest object is a developer's dream because you can:
Update web pages without reloading the page
Request data from the server after the page has loaded
Receive data from the server after the page has loaded
Send data to the server in the background
Create XMLHttpRequest object
All modern browsers (IE7+, Firefox, Chrome, Safari and Opera) have an in- Create an XMLHttpRequest object.
Syntax for creating XMLHttpRequest objects
Older versions of Internet Explorer (IE5 and IE6) use ActiveX objects:
To handle all modern browsers, including IE5 and IE6, please check if the browser supports XMLHttpRequest object. If supported, create an XMLHttpRequest object, if not supported, create an ActiveX object:
Instance
<!DOCTYPE html> <html> <head> <script> function loadXMLDoc() { if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","xmlhttp_info.txt",true); xmlhttp.send(); } </script> </head> <body> <h2>Using the XMLHttpRequest object</h2> <div id="myDiv"></div> <button type="button" onclick="loadXMLDoc()">Change Content</button> </body> </html>
Running Instance»
Click the "Run Instance" button to view the online instance
Send a request to the server
In order to send a request to the server, we use the XMLHttpRequest object The open() and send() methods:
xmlhttp.send();
Method | Description |
---|---|
open(method,url,async) | Specifies the type of request, URL, and whether the request should be processed asynchronously. method: Type of request: GET or POST url: The location of the file on the server async: true (asynchronous) or false (synchronous) |
send(string) | Send the request to the server. string: For POST requests only |
GET or POST?
GET is simpler and faster than POST and can be used in most situations.
However, always use POST requests in the following cases:
Cached files are not an option (updating files or databases on the server)
The amount of data sent to the server is large (POST has no size limit)
Send user input (can contain unknown characters), POST is more powerful and more powerful than GET Security
URL - File on the server
The url parameter of the open() method is the address of a file on the server:
The file can be any type of file (such as .txt and .xml), or a server Script files (such as .html and .php that perform actions on the server before sending a response back).
Asynchronous - True or False?
If you need to send a request asynchronously, the async parameter of the open() method must be set to true:
Sending asynchronous requests is a huge improvement for web developers. Many tasks performed on the server are very time-consuming.
By sending asynchronously, JavaScript does not need to wait for the server's response, but can be replaced with:
While waiting for the server's response, execute other scripts
Processing the response when the response is ready
Async=true
When using async=true, it is specified in the onreadystatechange event when the response is ready A function to be executed:
Instance
<!DOCTYPE html> <html> <head> <script> function loadXMLDoc() { if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","xmlhttp_info.txt",true); xmlhttp.send(); } </script> </head> <body> <h2>Using the XMLHttpRequest object</h2> <div id="myDiv"></div> <button type="button" onclick="loadXMLDoc()">Change Content</button> </body> </html>
Run Instance»
Click the "Run Instance" button to view the online instance
Async=false
If you need to use async=false, please change the third parameter of the open() method to false:
It is not recommended to use async=false, but it is still possible if you handle a few small requests.
Remember that JavaScript will not continue execution until the server response is ready. If the server is busy or slow, the application will hang or stop.
Note: Do not write onreadystatechange when you use async=false Functions - Just place the code after the send() statement:
Example
<!DOCTYPE html> <html> <head> <script> function loadXMLDoc() { xmlhttp=null; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } if (xmlhttp!=null) { xmlhttp.open("GET","xmlhttp_info.txt",false); xmlhttp.send(); document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } else { alert("Your browser does not support XMLHTTP."); } } </script> </head> <body> <h2>Using the XMLHttpRequest object</h2> <div id="myDiv"></div> <button type="button" onclick="loadXMLDoc()">Change Content</button> </body> </html>
Run Example»
Click the "Run Instance" button to view the online instance
Server response
To get a response from the server, use the responseText or responseXML property of the XMLHttpRequest object.
Properties | Description |
---|---|
responseText | Get the response data as a string |
responseXML | Get response data as XML data |
##responseText attributeIf the response from the server is not XML, use the responseText attribute. responseText property returns the response as a string, you can use it accordingly:
<!DOCTYPE html> <html> <head> <script> function loadXMLDoc() { if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","xmlhttp_info.txt",true); xmlhttp.send(); } </script> </head> <body> <h2>Using the XMLHttpRequest object</h2> <div id="myDiv"></div> <button type="button" onclick="loadXMLDoc()">Change Content</button> </body> </html>
Running Example »Click the "Run Instance" button to view the online instance
responseXML attributeIf the response from the server is not XML and you want To parse it into an XML object, use the responseXML attribute:
<!DOCTYPE html> <html> <head> <script> function loadXMLDoc() { xmlhttp=null; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } if (xmlhttp!=null) { xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { xmlDoc=xmlhttp.responseXML; var txt=""; x=xmlDoc.getElementsByTagName("ARTIST"); for (i=0;i<x.length;i++) { txt=txt + x[i].childNodes[0].nodeValue + "<br>"; } document.getElementById("myDiv").innerHTML=txt; } } xmlhttp.open("GET","cd_catalog.xml",true); xmlhttp.send(); } else { alert("Your browser does not support XMLHTTP."); } } </script> </head> <body> <h2>My CD Collection:</h2> <div id="myDiv"></div> <button type="button" onclick="loadXMLDoc()">Get my CD collection</button> </body> </html>
Run Instance»Click the "Run Instance" button to view the online instance
onreadystatechange eventWhen the request is sent to Server, we want to perform some action based on the response. onreadystatechange event is triggered every time readyState changes. The readyState attribute holds the status of XMLHttpRequest. Three important attributes of the XMLHttpRequest object:
Description | |
---|---|
The storage function (or the name of the function) is automatically called every time the readyState attribute changes | |
Stores the state of XMLHttpRequest. Change from 0 to 4: |
0: The request is not initialized 1: Server establishes connection 2: Request received 3: Process the request 4: Request completed and response ready |
200: "OK" |
404: Page not found |