0

I have attempted various solutions I have seen in other questions, but am not successfully logging data.ip.

When I log foo I only return undefined. Why is the ip property not being logged with async set to false?

TY

$.ajaxSetup({
  async: false
});

var getIp = function() {
  var ip;
  $.getJSON('//freegeoip.net/json/?callback=?', function(data) {
    ip = data.ip;
  });
  return ip;
}

var foo = getIp();
console.log(foo);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
DanMad
  • 1,643
  • 4
  • 23
  • 58

1 Answers1

2

You not implementing AJAX correctly. I changed your function so that it will return a Promise (note the return keywords in the function). Afterwards inside .then() you can pass a callback function which will be executed once the Ajax has finished.$.getJSON() is an implementation of Ajax (http://api.jquery.com/jquery.ajax/)

NOTE:

I strongly recommend NOT to use async: false inside any xhr / Ajax due to it will slow down your website. Better use the code below:

var getIp = function() {
  var ip;
  return $.getJSON('//freegeoip.net/json/?callback=?', function(data) {
    return data.ip;
  });
}

getIp().then(function(res) {
  console.log(res);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
messerbill
  • 5,499
  • 1
  • 27
  • 38