I know it looks like a duplicate question and believe me, I read all of them and tried everything, but I can't get this to work (JQuery 1.11.0):
function gip(){
var ccode;
$.ajax({
url: 'http://freegeoip.net/json/?callback=?',
dataType: 'json',
crossDomain: true,
async: false,
success: function (data) {
alert(data.country_code);
ccode = data.country_code;
},
error: function(error) {
alert(error)
return '';
}
});
alert(ccode);
return ccode;
}
No matter what I do, alert(ccode) fires before alert(data.country_code) so my return value is undefined. Unfortunately my knowledge is limited, and I can't see how I can do what I need in asynchronous mode. I simply need to return data.country_code.
2 Answers 2
First of all, since you are using jsonp, you can't do anything :(
As of version 1.8, async:false is no longer supported
You'll need to wait for success handler to get whatever value you are looking for.
11 Comments
async: false is supported in 1.11 and 2.x and is NOT deprecated yet. Even if he downgraded to 1.5, he wouldn't be able to send a synchronous jsonp request because it's jsonp, not because the library doesn't support it. It simply isn't possible due to how a jsonp request works.jsonp.It is not possible to send a synchronous jsonp request.
JSONP requests are done by appending a <script> tag to the <head> tag. Since it isn't possible to force a <script> tag to load synchronously after the DOM is ready, it isn't possible to force a jQuery jsonp request to be synchronous.
async:false. Don't wait for asynchronous operations to complete, use the response handlers they provide to respond to them.