Introduction
XMLHTTPRequest is an object which is used to perform the Asynchronous HTTP call using JavaScript. Usually, we call it an AJAX call. It is a browser object which is supported by all modern browsers and basically, it can handle any type of data which is used to communicate between the client and server using HTTP.
Asynchronous HTTP call
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8" />
- <title></title>
- </head>
- <body>
- <button id="btnAsync" type="button">Click Me</button>
- </body>
- <script>
- (function () {
- document.getElementById("btnAsync").addEventListener('click', makeRequest);
- function makeRequest() {
- var httpRequest = new XMLHttpRequest();
- if (!httpRequest) {
- alert(' Cannot create an XMLHTTP instance');
- return false;
- }
- httpRequest.onreadystatechange = function () {
- if (httpRequest.readyState === XMLHttpRequest.DONE) {
- if (httpRequest.status === 200) {
- alert(httpRequest.responseText);
- } else {
- alert('There was a problem with the request.');
- }
- }
- };
- httpRequest.open('GET', 'http://localhost:11207/api/Customer/CustomerDetails'); // service call
- httpRequest.send();
- }
- })();
- </script>
- </html>
httpRequest is an instance of XMLHttpRequest().
The open() is used to open the HTTP request to the server, It contains five parameters where three are optional parameters - httpRequest.open(type, URL, async, user, password)
- httpRequest.open('GET', 'http://localhost:11207/api/Customer/CustomerDetails');
From the above code, you can observe that we passed the type of request and the URL with the open method.
- Send( )- > It is basically used to post the data from the client to the server in the form of a query string, XML, JSON and so on
- Onreadystatechange -> This event will be fired once the server sends back the response based on the request
Conclusion
We saw how to perform an Ajax call in JavaScript using the XMLHTTPRequest object and different methods and events of the object which were used to make the successful Ajax call. I hope you have enjoyed this blog. Your valuable feedback, questions, or comments about this article are always welcomed.