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:
- The URL to send the request to
- The payload data
- A function callback
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:
- The URL to which we need to send the request
- The payload to send to the server in the form of an object
- The callback function to handle the response (from onreadystatechange callback). In this case, the callback simply logs the response to the browser console.