How do I chain consecutive ajax calls and pass values between them?

2260 views javascript
8

I have anonymous ajax function, which edits the response on success call. I want to pass the edited response to the next ajax function. Since I want both ajax function to be executed consecutively, I use .then(). Inside my first ajax function I edit the response, but when I pass it to the second ajax function, it gets passed unedited. So I guess I am passing the arguments in a wrong way.

Here is my code:

document.getElementById("div1").addEventListener("click", function (e) {
  e.preventDefault();
  $.ajax({
    url: 'www.randomURL.com',
    method: 'GET',
    crossDomain : true,
    xhrFields: {
      withCredentials: false
    },
    success: function(response){
      response = response.replace('random', 'semiRandom');
    }
  })
.then( function(){
  return $.ajax({
    //here response is still `www.randomURL.com` when I want it to be `www.semiRandomURL.com`
    url: response,
    method: 'GET',
    success: function(response) {
     //do something
    }
  });
});

How do I pass www.semirandom.com to the .then() function?

answered question

1 Answer

13

Return the value from first promise success handler to get it in the second function.

Updated code

document.getElementById("div1").addEventListener("click", function (e) {
  e.preventDefault();
  return $.ajax({
    url: 'www.randomURL.com',
    method: 'GET',
    crossDomain : true,
    xhrFields: {
      withCredentials: false
    },
    success: function(response){
      return response.replace('random', 'semiRandom');
    }
  })
.then( function(response){
  return $.ajax({
    //here response is still `www.randomURL.com` when I want it to be `www.semiRandomURL.com`
    url: response,
    method: 'GET',
    success: function(response) {
     //do something
    }
  });
});

Read more about promise chaining - https://javascript.info/promise-chaining

posted this

Have an answer?

JD

Please login first before posting an answer.