How to make AJAX Requests in JavaScript

Here’s a reusable JavaScript function that utilizes XMLHttpRequest object to make asynchronous requests to the server.

In the above example, we’ve got the sendAjaxRequest()function that performs the request, and below that, we’ve got our function call.

The function takes three parameters:

  1. The URL to send the request to
  2. The payload data
  3. A function callback

The function starts by checking the type of the ‘data‘ argument. If the data argument is a string, that string value directly gets assigned to the params variable. If the ‘data‘ argument is an object, then the JavaScript’s map function iterates over the object’s keys and builds a string of name-value pairs that can be assigned to the params variable. It’s this value that will later serve as the payload to the server.

var xhr = window.XMLHttpRequest … statement attempts to create a new XMLHttpRequest instance. If the browser natively supports the XMLHttpRequest object, it will be used. Otherwise, an ActiveXObject will be used (on older IE 5 and IE6 browsers).

xhr.open statement initializes a new POST request to the ‘url‘ parameter passed as the first argument to the function.

Then the function attaches XMLHttpRequest‘s onreadystatechange() event handler to the xhr instance. That will be called once the XMLHttpRequest‘s readystatechange event is fired. Within the event handler, it checks to see if the readyState property is greater than 3 and status is 200. If it does, then calls our success callback with the XMLHttpRequest’s responseText.

Below the onreadystatechange() event handler, xhr‘s setRequestHeader() method is used to set the appropriate request headers to the server. The first statement sets the ‘X-Requested-With‘ header, while the second statement sets the ‘Content-Type‘ header. The Content-Type header indicates to the server the type of data that is sent from the client. In our case, it is set to application/x-www-form-urlencoded. multipart/form-data, text/plain and application/json are other popular examples.

On line 15, the xhr.send() method dispatches the request, with ‘params‘ as the payload.

Finally, the xhr instance is returned to the caller.

The function call also has three parts to match with the function definition:

  1. The URL to which we need to send the request
  2. The payload to send to the server in the form of an object
  3. The callback function to handle the response (from onreadystatechange callback). In this case, the callback simply logs the response to the browser console.

Was this helpful?
+1
0
+1
1
+1
0
+1
0
+1
0
+1
0
+1
0