The core of AJAX is the XMLHttpRequest
object, which involves:
XMLHttpRequest
objectXMLHttpRequest
objectAll modern browsers support the XMLHttpRequest
object, which allows data exchange with a web server in the background.
This enables updating specific parts of a web page without reloading the entire page.
All modern browsers (Chrome, Firefox, IE, Edge, Safari, and Opera) come with a built-in XMLHttpRequest
object.
The syntax to create an XMLHttpRequest
object is:
variable = new XMLHttpRequest(); |
A callback function is a function provided as a parameter to another function.
Here, the callback function contains the code to run when the response is ready.
xhttp.onload = function() { // What to do when the response is ready } |
To send a request to a server, use the open()
and send()
methods of the XMLHttpRequest
object.
xhttp.open(“GET”, “ajax_info.txt”); xhttp.send(); |
// Create an XMLHttpRequest object const xhttp = new XMLHttpRequest(); // Define a callback function xhttp.onload = function() { // Here you can use the Data } // Send a request xhttp.open(“GET”, “ajax_info.txt”); xhttp.send(); |
Modern browsers restrict cross-domain access for security reasons, meaning the web page and the XML file it loads must reside on the same server.
For example, W3Schools examples load XML files from their own domain. To use similar examples on your own web pages, the XML files must be hosted on your server.
Method |
Description |
new XMLHttpRequest() |
Creates an instance of the |
abort() |
Aborts the ongoing request. |
getAllResponseHeaders() |
Retrieves header information. |
getResponseHeader() |
Retrieves specific header information. |
open(method, url, async, user, psw) |
Specifies the request details:
|
send() |
Sends the request to the server, typically used for GET requests. |
send(string) |
Sends the request to the server, typically used for POST requests. |
setRequestHeader() |
Adds a label/value pair to the request header. |
Property |
Description |
onload |
Defines a function to be executed when the request is completed (loaded). |
onreadystatechange |
Defines a function to be executed when the |
readyState |
Holds the status of the XMLHttpRequest:
|
responseText |
Returns the response data as a string. |
responseXML |
Returns the response data as XML. |
status |
Returns the status code of a request:
For a full list, refer to the HTTP Status Messages. |
statusText |
Returns the status text (e.g., “OK” or “Not Found”). |