0

I have a two ajax calls with json. The first helps me getting the globalVar value. The second takes this value, pass it to an argument in a remote url then returns a result.

var globalVar = "";

var firstRemoteUrl = "http://example.com/some/json";
        $.ajax({
            type: "GET",
            url: firstRemoteUrl ,
            dataType: 'jsonp',
            success: function (data) {
                globalVar = data;
            }
        });


var secondRemoteUrl = "http://example.com/another/json?var = " + globalVar;
        $.ajax({
            type: "GET",
            url: secondRemoteUrl ,
            dataType: 'jsonp',
            success: function (data) {
                alert(data);
            }
        });

The problem with these kind of calls is that the second ajax call doesn't wait until the first one achieves its call. So, sometimes, the globalVar is empty. Thus, the second call will not properly end.

I tried with async set ti false but, as it's indicated in the jquery documentation, the jsonp datatype ignore synchronous calls.

Is there a workarround for this issue?

Thanks,

Regards.

1
  • I found another workarround by adding a "wait": function pausecomp(millis) { var date = new Date(); var curDate = null; do { curDate = new Date(); } while(curDate-date < millis); } (found here: sean.co.uk/a/webdesign/javascriptdelay.shtm) Commented Jan 21, 2011 at 10:36

2 Answers 2

1

You could place the second call in the callback of the first one. It's a little messy but should get the job done. Something like this:

$.ajax({
 type: "GET",
 url: "http://example.com/some/json",
 dataType: 'jsonp',
 success: function(data) {
  $.ajax({
   type: "GET",
   url: "http://example.com/another/json?var = " + data,
   dataType: 'jsonp',
   success: function(result) {
    alert(result);
   }
  });
 }
});
Sign up to request clarification or add additional context in comments.

Comments

1

Place the second ajax call in the success callback function of first ajax call.

var firstRemoteUrl = "http://example.com/some/json";
    $.ajax({
        type: "GET",
        url: firstRemoteUrl ,
        dataType: 'jsonp',
        success: function (data) {
            globalVar = data;
            secondRemoteUrl = "http://example.com/another/json?var = " + globalVar;
                             $.ajax({
                                     type: "GET",
                                     url: secondRemoteUrl ,
                                      dataType: 'jsonp',
                                      success: function (data) {
                                                  alert(data);
                                                }
                                      });
                            }
          });

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.