1

I am a bit stuck with the below issue, my code is similar to this:

function (){
  var myVar = myFirstAjaxFunction()
  $.ajax({
    url: myUrl + myVar
    ....
  })
}

My first ajax function is returning a string that I would like to use in the end of my function, but I do not know how to wait for the first function to be done.

I hope this is clear, thanks for your help!

Tamas Szoke
  • 5,426
  • 4
  • 24
  • 39
Nefarious62
  • 161
  • 1
  • 5
  • 15
  • 1
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Ivar Mar 10 '20 at 09:49

5 Answers5

1

Here is an example:

$.ajax({
    success: function (data) {
        var a = data;
        $.ajax({
            data: 'data=' + a,
            success: function (data2) {

            }
        });
    }
});

Or you pass callback :

function myFirstAjaxFunction (callback){

$.ajax({
    success: function (data) {
     callback(data);
   }
});

}

and usage :

myFirstAjaxFunction(function(data){
//call 2nd ajax
});
AmirNorouzpour
  • 1,119
  • 1
  • 11
  • 26
1
$.post(url1,{ params:myVar}, function(result) {
    $.post(url2,{params:result}, function(final_result) {
       //use final_result here... :)
    });
});
Dan Linh
  • 129
  • 1
  • 7
1

I think you should take help of callback function, please look at the below code. will help you.

function myFirstAjaxFunction(callback){
    $.ajax({
        url: "demo_test.txt",
        success: function(result){
         return callback('your-string');
        }
    });
}

function (){
  myFirstAjaxFunction(function(myVar){
  $.ajax({
    url: myUrl + myVar
    ....
  })
 })
} 
0

You can use Async/Await:

async function (){
  var myVar = await $.ajax({
    url: firstAjaxCallUrl
    ....
  })
  $.ajax({
    url: myUrl + myVar
    ....
  })
}
Tamas Szoke
  • 5,426
  • 4
  • 24
  • 39
0

Return the promise from the ajax call. Example snippet for your reference

function (){
   myFirstAjaxFunction()
}

function myFirstAjaxFunction() {
  $.ajax({
    url: '',
    success: function(response) {
      //response of the first api call
      secondApiCall(responseoffirst);
    }
  });
}

function secondApiCall(value) {
  $.ajax({
    url: '',
    success: function(response) {
      console.log(response);
    }
  });
}

joy08
  • 9,004
  • 8
  • 38
  • 73