While it's not a recommended way of doing things, performing a synchronous Ajax call should solve the issue as you perceive it.
ip = null;
$.ajax({
url: 'http://jsonip.appspot.com/',
async: false,
dataType: 'json',
contentType: 'application/j-son;charset=UTF-8',
success: function (data) {
ip = data.ip
alert(ip);
}
});
alert(ip);
Again, I highly stress that this is NOT recommended, as performing synchronous Ajax (which stands for Asynchronous Javascript And Xml) is irregular and kinda defeats the purpose of Ajax. But, if you absolutely need your web app to wait for that data to be returned, doing it this way should work. I'd make a fiddle of it, but the URL doesn't allow requests from jsfiddle.
It would be better if you could code your app such that it isn't dependent upon the response to continue execution. For example, if you called a function after the successful return of the Ajax response, like this:
ip = null;
$.ajax({
url: 'http://jsonip.appspot.com/',
dataType: 'json',
contentType: 'application/j-son;charset=UTF-8',
success: function (data) {
ip = data.ip
alert(ip);
gotAjaxResponse()
}
});
function gotAjaxResponse() {
alert(ip);
}
Note we are still using the global variable ip
(which is another bad practice, but I'll save that speech for another day =), at least you are waiting for a response before continuing on to the code that depends on having that data.
Additionally, note that the second example still uses the generic $.ajax()
, without the async: false
, you can use the $.getJSON()
method.