How can I use an URL obtained through a jQuery.get call to carry out another call?

Viewed 21

Basically, what I'm trying to do is this:

var mydata = null;
jQuery.get(ANOTHER_URL, function(data) {
    mydata = data;
}).then(jQuery.get(parsingFunction(mydata), function(otherData) {/*do stuff with otherData*/}));

parsingFunction(notYetAnURL) {
   /*does stuff with notYetAnUrl*/
   return nowIsURL;
}

The issue is.. this doesn't work. When the second jQuery.get call happens, mydata appears to still be null. I'm new to Ajax and asynchronous programming in general, so I apologize if the question may seem dumb, but I really can't get out of this. Could anybody kindly help?

1 Answers

You are not using a callback function for your result. So it is good to use .done and .fail functionality with callback functions for better readability and error catch.

function firstService(){
  jQuery.get(ANOTHER_URL)
    .done(function(data){
      // first result
      if(data){
        secondService(data);
      }
    })
    .fail(function(xhr, status, error) {
      console.log(xhr);
      console.log(status);
      console.error(error);
  });
}

function secondService(newData){
  jQuery.get(getSecondServiceUrlFromData(newData))
    .done(function(data){
      // second result
    })
    .fail(function(xhr, status, error) {
      console.log(xhr);
      console.log(status);
      console.error(error);
  });
}

function getSecondServiceUrlFromData(data) {
   /*does stuff with notYetAnUrl*/
   return nowIsURL;
}

firstService();
Related