How to make two AJAX Calls

Hey guys, I am trying to make two ajax calls from two different apis in JavaScript without jQuery?

var requestW = new XMLHttpRequest();
  requestW.open('GET', link);
  requestW.onload = function(){
  };
   requestW.send();

This is for one, how can i have two links, because when i put two of this they are not parallel.

First, you don’t want to use XMLHttpRequest. It’s an old, horrible API. The fetch API is well supported and much easier to use. Using XHR will result in code that is, at best, ugly, but also bug-prone.

Now, what do you need from the two AJAX calls? Do you need one after the other? This is easy to do with fetch:

fetch(firstURL)
    .then(handleResponse)
    .then(function(data) {
        // handle data from first response
        return fetch(secondURL)  // << make the second call here
     )
    .then(handleResponse)  // treat the second response just like the first
    .then(function(data) {
        // handle data from second response
    )
    .catch(function handleError(error) {
        // handle error from either response
    )

function handleResponse(response) {
        if(response.ok) return response.json();
        throw new Error(response.message);
}

If you’ve never used promises before, it can take a little bit to get your head around. The handleResponse function is necessary with the fetch API because of the way it formats the server’s response.

If, for some arcane reason, you really need to use XHR, just abstract the logic into a function and call it as many times as you need.

function createRequest(url, cb) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url);
    xhr.onload = function() {
        cb(this.responseText);
    };
    xhr.send()
}

createRequest(firstURL, function(firstResponse) {
    // handle first response data
    createRequest(secondURL, function(secondResponse) {
        // handle second response data
    }
}

It’s also quite possible to create your own promise wrapper for this to make the code much cleaner.

1 Like

Thanks. It was helpful!!!