0

What am I doing wrong here?

var country = function () {
  var tmp = null;
  $.ajax({
    'async': false,
    'dataType': 'jsonp',
    'url': "http://ipinfo.io",
    'success': function (data) {
      tmp = data.country;
    }
  });
  return tmp;
}();

console.log(country);

prints null

async is set to false, so it should work? What is wrong here?

BTW if I put console.log(data.country) inside success call it prints the country correcty

OutFall
  • 497
  • 5
  • 18
  • Eeeck. Please don't use `async: false`. That just locks up the browser and is the wrong way to program ajax calls and won't work with JSONP calls either. – jfriend00 Apr 23 '14 at 20:44

3 Answers3

2

async:false won't work with jsonp requests.

See the documentation for the async setting.

But really, you should avoid async:false anyway.

Jason P
  • 26,608
  • 3
  • 29
  • 44
0

JavaScript is asynchronous. Your country method is returning tmp before the ajax call comes back successfully.

Look into promises or deferred objects.

var country = function () {
    return  $.ajax({
        'dataType': 'jsonp',
        'url': "http://ipinfo.io"
    });
}

country().done(function(data) {
   console.log(data);
})
.fail(function(){

});
VtoCorleone
  • 14,341
  • 4
  • 33
  • 48
0
var country = function () {
  var tmp = null;
  $.ajax({    
    dataType: 'json',
    url: "http://ipinfo.io",
    success: function (data) {
      tmp = data.country;
    },
    async: false    
  });
  return tmp;
}();
Md. Rahman
  • 1,682
  • 12
  • 15
  • 1
    So you've basically just changed `jsonp` to `json`? It would be nice to provide some textual description. – Mifeet Apr 23 '14 at 21:25