What is XMLHttpRequest?
XMLHttpRequest is an object built into the browser that allows you to make HTTP requests to the server without reloading the page. XMLHttpRequest is mostly used in Ajax programming. XMLHttpRequest can send and retrie any type of data including JSON, XML, text, etc. XMLHTTPRequest is used for asynchronous communications between clients and servers. XMLHttpRequest is used mainly for historical reasons, as there is a lot of legacy code based on XMLHttpRequest, as well as the need to support older browsers.
- There is a lot of XMLHttpRequest legacy code that needs to be supported
- The need to support older browsers without the use of polyfills
- The fetch method cannot yet provide tracking of the progress of sending to the server
How to send GET request using the XMLHttpRequest?
To send an HTTP GET request using the XMLHttpRequest, we need to first create an object by calling new XMLHttpRequest() and then use the XMLHttpRequest open() and send() methods. Onreadystatechange informs when the status of a request has changed. Below is an example of getting JSON from the ReqBin echo URL with XMLHttpRequest object.
How to send GET request using the Fetch API?
Fetch API is a powerful new web API that allows you to make asynchronous requests. The Fetch API provides a more effective and flexible set of features than the XMLHttpRequest object. Fetch returns a "promise," which is one of the new ES6 features. Promises allow you to process an asynchronous request more intelligently. Below is an example of making GET a request to the ReqBin echo URL with Fetch API.
How to send GET request using the jQuery Ajax?
If you are using jQuery in your project, it is recommended to use the jQuery Ajax methods instead of the raw XMLHttpRequest object. The jQuery $.get() method allows you to get from the server in a single line. This is a simple wrapper for the more advanced $.ajax method. Below is an example of getting JSON from the ReqBin echo URL with the jQuery Ajax method.
How to send GET request using the Axios?