XMLHttpRequest in JavaScript

XMLHttpRequest is an object in JavaScript that allows you to send AJAX requests to the server, it allows you to get a response from the server using an asynchronous process. Asynchronous calls allow you to get a response from the server without having to reload the page. Imagine a social media website that automatically/dynamically updates your feed without you having to reload the page or tells you there are new posts available for you to update. This is an example of how AJAX can asynchronous server calls can be used.

The below code shows a basic XMLHttpRequest in JavaScript. First, you need to create a new XMLHttpRequest object using the ‘new’ keyword. Then we modify its ‘onreadystatechange’ event to log out the response from the request to the developer console. Within this event, there is an if statement that checks the ‘readyState’ and ‘status’ fields of the XMLHttpRequest object, these two checks ensures that the request is completed and has been successful. After we then call the ‘open’ function on the object and give it a request method of “GET” and a file we want to access on the server. Finally, we send the request. Opening and sending the request and similar to like opening your phone app, or phonebook, and then actually making a phone call. For this example, the contents of the text file “my_info.txt” will be returned and printed to the developer console.

You can also send a request to a PHP file too. The PHP file could include some sort of process you want to execute, such as retrieving information from the database. When we request a server-side script, such as a PHP file, the file will be executed and its result will be returned to our AJAX request. Imagine the contents of the ‘ajax_request.php’ included getting some information from the database and then printing that information, this process will then be executed and printed to the file contents, then similarly to the previous example the contents of this file will be returned and printed to the developer console.

Using an XMLHttpRequest you can also send information to the server. You may need/want to do this when sending data to the server to be processed on the database or on a server-side process. For example, we could create an object that contains some data we wish to send to the server.

The below example shows an example of an XMLHttpRequest that sends data to an endpoint. Instead of sending the request using a ‘GET’ method it uses a ‘POST’ method, and sends the request to an endpoint called ‘/adduser’. The variable called ‘data’ is sent on the request by passing it into the send function. This will send the data to the endpoint and return the response in the ‘onreadystatechange’ event listener.

Leave a Reply