skip to Main Content

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!

5

Answers


  1. You can use Async/Await:

    async function (){
      var myVar = await $.ajax({
        url: firstAjaxCallUrl
        ....
      })
      $.ajax({
        url: myUrl + myVar
        ....
      })
    }
    
    Login or Signup to reply.
  2. 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
    });
    
    Login or Signup to reply.
  3. 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);
        }
      });
    }
    
    
    Login or Signup to reply.
  4. $.post(url1,{ params:myVar}, function(result) {
        $.post(url2,{params:result}, function(final_result) {
           //use final_result here... :)
        });
    });
    
    Login or Signup to reply.
  5. 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
        ....
      })
     })
    } 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search