HMLHttpRequest is part of AJAX which are web development techniques which can be used to develop asynchronous web apps. On asynchronous web pages we can send and receive data from servers and update web pages without reloading the web pages.
The request sent by XMLHttpRequest can either be a GET or POST request. We can GET in most cases but POST is more secure and should be used whenever we have large amounts of data or unknown user input.
Sending a POST request using XMLHttpRequest
To send a request through XMLHttpRequest we first need to make a new XMLHttpRequest object:
To send a request we need to use the open() and send() methods. The open() method takes three parameters which are the method (GET/POST), URL (file location on server) and a Boolean value for asynchronous or synchronous nature of the request:
For a synchronous request:
With asynchronous requests JavaScript does not wait for the request to complete and can run other scripts while the request is being completed. It is not recommended to use synchronous requests as the web app can come to a complete halt if the server is busy.
Before sending the data by the send() method we can also use the setRequestHeader() to send the data like an HTML form with a header name and a header value:
Now we can send data with an optional parameter which specifies the body of the request:
The onreadystatechange property can be used on the XMLHttpRequest object to execute a function once a response has been received from the server:
if (this.readyState == XMLHttpRequest.DONE && this.status == 200) {
//Code to be Executed once request is finished
}
};
All in all, a simple asynchronous POST request using XMLHttpRequest will look something like this:
request.open("POST", "File_Path", true);
request.setRequestHeader(header, value);
request.onreadystatechange => {
if (this.readyState == XMLHttpRequest.DONE && this.status == 200) {
//Code to be Executed once request is finished
}
};
request.send(body);
Conclusion
AJAX’s XMLHttpRequest can be used to send and receive data from the server and update the web page according to it. This technique is pure gold for developers as they can do all this without having to reload the page.