0

This is my code:

var user_ip ="not found";

$.get("http://ipinfo.io", function(response) {
   var user_ip=response.ip; 
   alert("on line 749 user ip is " + user_ip);
}, "jsonp");
alert("on line 751 user ip is " + user_ip);

Yet my user ip only get saved within the .get, afterwards it always reverts to "not found".

I know this involves using a call back to save the data but cant find an example of how to do it that makes sense to me

huysentruitw
  • 27,376
  • 9
  • 90
  • 133

1 Answers1

0

That's because the callback is executed asynchronously, way after

alert("on line 751 user ip is " + user_ip);

has been executed.

You could do a synchronous GET request as demonstrated here but I consider synchronous code as bad practice :)

A second problem is that you redeclare user_ip inside the scope of the callback function, which means that the global user_ip will not be overridden as you might have intended.

Community
  • 1
  • 1
huysentruitw
  • 27,376
  • 9
  • 90
  • 133
  • Hi, if you consider synchronous code as bad practice what is a solution then? not declaring user_ip beforehand doesnt solve the problem. –  Sep 24 '14 at 18:13
  • well, you get the user_ip in the callback, so you have what you want :) What do you want to do with the ip afterwards? – huysentruitw Sep 24 '14 at 18:14
  • I want to use it as a variable for a string that I need later in the script . –  Sep 24 '14 at 18:18
  • make your code asynchronous and all your problems will disappear. Check out [`$.Deferred`](http://learn.jquery.com/code-organization/deferreds/examples/) and read about promises. – huysentruitw Sep 24 '14 at 18:21
  • If you tell me _what_ you'll do with `user_ip` I could give you a concrete example. – huysentruitw Sep 24 '14 at 18:24
  • I want to send the ip number along with other variables to google analytics. but I want to send it to google analytics even if the call to get the ip fails. –  Sep 25 '14 at 17:58
  • Then use `done` and `fail` functions: `$.get(...).done(function (ip){sendToAnalytics}).fail(function(){sendToAnalytics});` – huysentruitw Sep 25 '14 at 20:52