How to make synchronous JSONP crossdomain call

As explained by zi42, and by the jQuery.ajax() documentation, ‘Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation.’

This is not a bad thing, given that a synchronous call tends to result in a poor user experience because it locks up the browser until the response comes back, so I’d steer clear of making a synchronous call even with standard Ajax where it is easy to implement. You want to make two synchronous calls in a row so that would be even worse.

The workaround zi42 suggested in a comment – making a synchronous Ajax call to your own domain and then making the cross-domain call from your server – is the best approach you could take if you really want it to be synchronous.

The other obvious approach is to restructure your code so that it will work asynchronously, by putting the stuff you want to do after each jsonp request into the success callback. That is, within the success callback of the first jsonp request you’d go on to make the second jsonp request. Within the success callback of the second you’d do any final processing. If you need to pass the final results to another part of your code then put the Ajax code in a function that takes a callback as a parameter:

function doMyAjaxCalls(callbackFunc) {
   // make first request
   $.ajax({
      ...
      dataType: "jsonp",
      success: function(data, textStatus, jqXHR) {
         // do something with first response, then
         // make second request              
         $.ajax({
            ...
            dataType: "jsonp",
            success: function(data, textStatus, jqXHR) {
               // do something with second response, then
               // do final processing, then
               callbackFunc(dataHere);
            }
         });
      }
   });
}

doMyAjaxCalls(function(response) {
   // do something with response
});

Leave a Comment