What is JavaScript?
JavaScript is a scripting language that works both on the client-side (in browsers) and on the server-side (Node.js). JavaScript code is called a script. JavaScript scripts can manipulate the content of a web page, interact with the user, process mouse clicks, and post requests to the server using the XMLHttpRequest object or the Fetch API.
What is XMLHttpRequest?
XMLHttpRequest is a built-in browser object that is used to communicate with the server in pure JavaScript. With the XMLHttpRequest object, you can receive data from the server or send data to the server using the XMLHttpRequest object without reloading the entire web page. XMLHttpRequest is mainly used in AJAX programming. Today there is a more modern way to send requests to the server: Fetch API. 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.
When to choose XMLHttpRequest over Fetch API?
- Need to support older browsers but avoid using polyfills.
- For historical reasons, there is a lot of code that uses XMLHttpRequest that needs to be supported
- The Fetch API cannot yet provide tracking of the progress of sending to the server
How to use XMLHttpRequest?
XMLHttpRequest has two modes of operation: asynchronous and synchronous. In most cases, asynchronous requests are used. To make a request, we need to follow these steps:
1. Create an XMLHttpRequest object
2. Initialize the created object using the xhr.open() method:
Where:
- method: HTTP method
- URL: the URI where the request is sent (string or a URL object)
- async (optional): if set to false, then the request will be executed synchronously (default true)
- user, password (optional): login and password for basic HTTP authorization
3. Submit an request usin the xhr.send() method:
The optional body parameter contains POST, PUT, and PATCH requests data. Some request types, such as GET, HEAD do not have a body.
You need to listen to events on the xhr object in order to be notified when the status of a request changes. The most used events are:
- xhr.onload: occurs when any response is received from the server, including HTTP error responses
- xhr.onprogress: occurs periodically during a response (useful for showing the progress of the request)
- xhr.onreadystatechange: notifies when the status of an XMLHttpRequest has changed (e.g. the request has completed)
- xhr.onerror: indicates that the request could not be completed, for example, a connection could not be established or an invalid URL was specified
4. If you need to cancel the request, you can use the xhr.abort() method. This method generates an abort event and sets xhr.status to 0.
JavaScript XMLHttpRequest Request Examples
An example of sending a GET request to the ReqBin echo URL.
JavaScript XMLHttpRequest Asynchronous Request Example
XMLHttpRequest always sends an asynchronous request unless otherwise specified. Below is an example of an async request to the ReqBin echo URL with XMLHttpRequest object:
JavaScript XMLHttpRequest Synchronous Request Example
If the third parameter async is set to false in the xhr.open() method, the request is executed synchronously. In other words, JavaScript execution stops at xhr.send() and resumes when the response is received. Synchronous requests can be useful for debugging your code. It is not recommended to use synchronous requests on your production site as it can negatively impact your app's performance and user experience.
Synchronous XMLHttpRequest requests are rarely used because they block JavaScript execution until the request is complete. If the synchronous request takes too long for some reason, the browser will offer to close the “hung” page. Many advanced features of XMLHttpRequest, such as making a request to a different domain or setting a timeout, are not available for synchronous requests.
How to post JSON data using XMLHttpRequest?
To post data using a JavaScript XMLHttpRequest object, you need to pass an HTTP POST method when calling the xhr.open("POST", URL) method. To post data in JSON format using XMLHttpRequest, you need to convert the JavaScript object to a string using the JSON.stringify() method and provide a "Content-Type: application/json" header along with your request. Below is an example of sending JSON data to the ReqBin echo URL:
How to post HTML Form data using XMLHttpRequest?
To post HTML data with a JavaScript XMLHttpRequest object, you need to set "Content-Type" to "application/x-www-form-urlencoded" and pass the form data as key=value pairs to the xhr.send() method. Below is an example of sending HTML Form data to the ReqBin echo URL.
How to post XML data using XMLHttpRequest?
To send data in XML format using a JavaScript XMLHttpRequest object, you need to set "Content-Type" to "application/xml" and pass XML string to the xhr.send() method. Below is an example of sending XML data to the ReqBin echo URL.
How to set a timeout on XMLHttpRequest?
You can use the xhr.timeout property to set a timeout for an XMLHttpRequest. The timeout is specified in milliseconds. The default value is 0, which means the request has no timeout.