The cornerstone of AJAX is the XMLHttpRequest object.
1. Create an XMLHttpRequest object
2. Define the callback function
3. Open the XMLHttpRequest object
4. Send a request to the server
All modern browsers support the XMLHttpRequest
object.
The
XMLHttpRequest
object can be used to exchange data with a web server behind the scenes. This means that parts of a web page can be updated without reloading the entire page.
All modern browsers (Chrome, Firefox, IE, Edge, Safari, Opera) have a built-in XMLHttpRequest
object.
Syntax for creating XMLHttpRequest
object:
variable= new XMLHttpRequest();
Define callback function
A callback function is a function passed as an argument to another function.
In this case, the callback function should contain code to be executed when the response is ready.
xhttp.onload = function() {
// What to do when the response is ready
}
Send request
To send a request to the server, you can use the open() and send() methods of the XMLHttpRequest
object:
xhttp.open(“GET”, “ajax_info.txt”);
xhttp. send();
<!DOCTYPE html> <html> <body> <h2>The XMLHttpRequest Object</h2> <div id="demo"> <p>Let AJAX change this text.</p> <button type="button" onclick="loadDoc()">Change Content</button> </div> <script> function loadDoc() { const xhttp = new XMLHttpRequest(); xhttp.onload = function() { document.getElementById("demo").innerHTML = this.responseText; } xhttp.open("GET", "ajax_info.txt"); xhttp. send(); } </script> </body> </html>
Cross-domain access
For security reasons, modern browsers do not allow cross-origin access.
This means that the web page and the XML file it is trying to load must be on the same server.
The examples on W3Schools all open XML files located in the W3Schools domain.
If you want to use the example above on one of your own web pages, the XML file you load must be on your own server.
XMLHttpRequest Object Methods XMLHttpRequest Object Methods
Method |
Description |
new XMLHttpRequest() | Create a new XMLHttpRequest object |
abort() | ? Cancel the current request |
getAllResponseHeaders() | Return header information |
getResponseHeader() | ? Return specific header information |
open(method, url, async, user, psw) |
. Specifies the request. method: the request type GET or POST |
send() | Send the request to the server for GET requests |
send(string) | Send the request to the server. For POST requests |
setRequestHeader() | Add tag/value pairs to headers to be sent |
XMLHttpRequest Object Properties XMLHttpRequest object properties
Attribute |
Description |
onload | Defines the function to be called when receiving (loading) a request. |
onreadystatechange | Define the function to be called when the readyState property changes |
readyState |
Save the state of XMLHttpRequest. 0: request not initialized 1: The server connection is established 2: Request received 3: Process the request 4: The request is complete and the response is ready |
responseText | Return the response data as a string |
responseXML | Return response data as XML data |
status |
Returns the status number of the request 200: “OK 403: “Forbidden” “404: “Not Found” For a full list, See Http Messages Reference HTTP Messages |
statusText | ? Returns the status text (eg: “normal” or “not found”) |
The onload Property onload attribute
Using the XMLHttpRequest
object, you can define a callback function to be executed when the request is answered.
This function is defined in the
onload
attribute of theXMLHttpRequest
object:<!DOCTYPE html> <html> <body> <div id="demo"> <h2>The XMLHttpRequest Object</h2> <button type="button" onclick="loadDoc()">Change Content</button> </div> <script> function loadDoc() { const xhttp = new XMLHttpRequest(); xhttp.onload = function() { document.getElementById("demo").innerHTML = this. responseText; } xhttp.open("GET", "ajax_info.txt"); xhttp. send(); } </script> </body> </html>
Multiple Callback Functions Multiple callback functions
If there are multiple AJAX tasks in the website, you should create a function to execute the XMLHttpRequest
object, and create a callback function for each AJAX task.
The function call should contain the URL and the function to call when the response is ready.
loadDoc("url-1", myFunction1); loadDoc("url-2", myFunction2); function loadDoc(url, cFunction) { const xhttp = new XMLHttpRequest(); xhttp.onload = function() {cFunction(this);} xhttp.open("GET", url); xhttp. send(); } function myFunction1(xhttp) { // action goes here } function myFunction2(xhttp) { // action goes here }
The onreadystatechange Property onreadystatechange property
The
readyState
attribute holds the state of the XMLHttpRequest.
The
onreadystatechange
attribute defines a callback function that is executed when the readyState changes.
The
status
and statusText
attributes hold the status of the XMLHttpRequest object.
Attribute |
Description |
onreadystatechange | Define the function to be called when the readyState property changes |
readyState |
Save the state of XMLHttpRequest. 0: request not initialized 1: The server connection is established 2: Request received 3: Process the request 4: The request is complete and the response is ready |
status |
Returns the status number of the request 200: “OK 403: “Forbidden” “404: “Not Found” For a full list, See Http Messages Reference HTTP Messages |
statusText | ? Returns the status text (eg: “normal” or “not found”) |
The onreadystatechange
function is called every time the readyState changes.
Response is ready when readyState
is 4 and status is 200:
<!DOCTYPE html> <html> <body> <div id="demo"> <h2>The XMLHttpRequest Object</h2> <button type="button" onclick="loadDoc()">Change Content</button> </div> <script> function loadDoc() { const xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this. readyState == 4 & amp; & amp; this. status == 200) { document.getElementById("demo").innerHTML = this. responseText; } }; xhttp.open("GET", "ajax_info.txt"); xhttp. send(); } </script> </body> </html>
Notice
The
onreadystatechange
event is fired four times (1-4), once for each readyState change.
Reference address: AJAX The XMLHttpRequest Object