XHR AJAX calls in JavaScript

Quang Nguyen
Sep 3, 2018 · 2 min read

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!

quangtn0018

Just my findings and techniques that I’ve learned from working and doing side projects on all things software engineering related

Quang Nguyen

Written by

Software Engineer

quangtn0018

Just my findings and techniques that I’ve learned from working and doing side projects on all things software engineering related

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade