XHR AJAX calls in JavaScript

Quang Nguyen
quangtn0018
Published in
2 min readSep 3, 2018

Today, I will be showing you guys how to make an XHR AJAX request to do RESTful API calls like ‘GET’ and ‘POST’ to your end points.

I recently had to do this while creating an admin site at work and I would like to share it with all of you how to do it!

Let’s get started!

In your html, you would have a basic form with a submit button with a function attached to the form that we will setup in our ajax.js below.

// ajax.jsfunction sendData(event, postURL) {    event.preventDefault()    var xhr = new XMLHttpRequest()    xhr.open('POST', postURL, true)    xhr.onreadystatechange = function () {       if (xhr.readyState === 4) {          if (xhr.status === 200) {            alert("Send input data was successful")          } else {            alert("There was a problem sending input data. Please try again")          }
}
}
var formData = new FormData( document.getElementById(formID) ); xhr.send(formData);}

So what we have here is a simple submit function when we click on the submit button in the html file. As you can see, we create a new XMLHttpRequest object in order to set up an HTTP request. Basically, this object will let you make an HTTP request (e.g post). xhr.open(‘POST’, postURL, true) this line is pretty self-explanatory. We open a POST request with the provided postURL or endpoint. The last argument for this call is to tell the request that it will be an AJAX call.

The xhr.onreadystatechange function is a callback once the AJAX call finishes with the request so it is important that this function comes before sending the form data. If the function was placed after sending the data, you would not receive a message whether the data was sent successfully or not. To learn more about how to send multi-part data, check out my post on it here.

And that’s all there is to creating an AJAX call. Very simple and easy!

--

--