JayDoe
JayDoe

Reputation: 3

Setting Variable During Callback

The following jQuery code attempts to store a client's IP address in a global variable during the callback for an ajax GET request.

Code

  var userip = null;
  $.ajax({
    url: "http://ipinfo.io",
    type: 'get',
    dataType: 'jsonp',
    async: false,
    success: function(data) {
      userip = data.ip;
      console.log(userip); // prints unique ip address
    }
  }).done(console.log(userip)); // prints null

Knowing that GET requests are usually executed asynchronously (but requiring otherwise), I have marked async: false in the JSON spec. For added measure, I call done() to ensure the request has finished before continuing.

Nevertheless, printing userip returns null after the GET request but prints the unique client IP during the ajax success callback.

Any explanation would be greatly appreciated. Thanks in advance.

Upvotes: 0

Views: 46

Answers (3)

Jaydo
Jaydo

Reputation: 1859

Try this

var userip = null;
  $.ajax({
  url: "http://ipinfo.io",
  type: 'get',
  dataType: 'jsonp',
  async: false,
  success: function (data) {
    userip = data.ip;
    console.log(userip); // prints unique ip address
  },
  complete: function () {
    console.log(userip); // prints unique ip address
  }
});

Upvotes: 0

Antiokus
Antiokus

Reputation: 544

what you're doing is making the console.log(userip) execute immediately, and not after the request is completed. Which is why userip gets stored properly in the success handler. Think of done as what to do once the request is completed. It needs to execute an action (function). You're passing a statement (console.log(userip)) which actually returns undefined. So done doesn't do anything.

try this instead

}).done(function() {
    console.log(userip);
});

Upvotes: 0

Cameron
Cameron

Reputation: 434

.done() expects a callback. Try swapping out

console.log(userip)

with

function() { console.log(userip); }

Upvotes: 1

Related Questions