-2

My goal is to get the user's ip address with jQuery or Javascript without using some other library or anything like that, store it as a variable, then use that variable later. I've looked and looked, but I've only found solutions like getjson or ajax which would have the variable inside of a function - not usable elsewhere.

This is the nicest that I've been able to get on my own, which isn't much better than any other solution:

$.ajax({
  type: "POST",  
  url: "datascripts/ip.php",
  data: {get:"ip"},
  dataType: "json",
  context: document.body,
  async: true,
  success: function(res, stato) {
    var ip = res.ip;
  },
  error: function(res, stato) {
    alert("IP thing didn't work.");
  }
});
alert(ip);

That doesn't do anything though, since the variable is set inside of the ajax function and doesn't seem to exist outside of it.

If I change the success function to:

  success: function(res, stato) {
    alert(res.ip);
  }

Then that works just fine - I get the correct IP.

I imagine that this could be fixed simply with making the ip variable a global variable, but that hasn't been working either - not sure why.

I've tried a few different things to make the IP variable global:

  • Declaring the variable (var ip; / var ip = "";) before the ajax
  • Making it global by using the window object, only inside the ajax or before (window.ip = res.ip;)
zbee
  • 959
  • 1
  • 7
  • 29
  • make alert in success callback, you are alerting variable before request is returned from server – Justinas Jul 23 '14 at 14:21
  • 1
    You need to read up on **variable scope**. Since you haven't included your attempt at declaring the variable as global, I assume you've done it incorrectly. Define the variable outside the `$.ajax()` block and you should be able to access it on the same scope level. – esqew Jul 23 '14 at 14:21
  • @Justinas I'm not actually wanting to alert the IP. I want to store the IP as a variable and use it later. – zbee Jul 23 '14 at 14:22
  • What is the actual problem? You're kind of talking in circles. You got a solution you say, **how is it not working**? If you log/alert the ip var within success, does the ip address appear? – Jonast92 Jul 23 '14 at 14:23
  • @esqew So, declare the variable before the ajax (var ip;), do the ajax and set ip = res.ip, then it should work? Because, I've done that, with no luck. – zbee Jul 23 '14 at 14:23
  • @Jonast92 I can alert the IP address from inside the ajax, so I know I can get the IP, but I want to store it in a variable and use it much later in my code. – zbee Jul 23 '14 at 14:24
  • It all depends on the scope of where you declare that `var ip`. If you store it in a level above the `$.ajax()` directive, you'll only be able to access it in that level. Put it at the very beginning of your script and see what happens (it should be accessible to all child-levels of your code, but not to the parent/sibling levels). – esqew Jul 23 '14 at 14:25
  • This could be a nice read about why it did not work http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call – Spokey Jul 23 '14 at 14:25
  • possible duplicate of [How to return an array from jQuery ajax success function properly?](http://stackoverflow.com/questions/2195161/how-to-return-an-array-from-jquery-ajax-success-function-properly) – Frank van Puffelen Jul 23 '14 at 15:29

1 Answers1

3

Note this will only populate the ip variable once the ajax returns successfully. You cannot use it before that so perhaps you can make a callback

var ip;
$.ajax({
  type: "POST",  
  url: "datascripts/ip.php",
  data: {get:"ip"},
  dataType: "json",
  context: document.body,
  async: true,
  success: function(res, stato) {
    ip = res.ip;
    myCallback();
  },
  error: function(res, stato) {
    alert("IP thing didn't work.");
  }
});

function myCallback(){
    // Do whatever you want with ip here.
    console.log(ip);
}
Rob Schmuecker
  • 8,934
  • 2
  • 18
  • 34
  • It really does depend on the context (where OP wants to utilize the variable) but this is a good general answer. The variable must be defined outside the scope of the `$.ajax()` directive in order to use it in such a scope. – esqew Jul 23 '14 at 14:26
  • @esqew Yeah, I upvoted your original comment based on these sentiments! – Rob Schmuecker Jul 23 '14 at 14:27
  • Well, my code is going through and setting up a few dozen variables with user info, then at the end I'm sending it to PHP - That's when I want to use the ip variable. – zbee Jul 23 '14 at 14:27
  • 1
    You want to send the IP to PHP? You don't have to, by virtue of the fact that PHP can detect it then! – Rob Schmuecker Jul 23 '14 at 14:30
  • @RobSchmuecker This script is going to be included from an external source once it's used (example.com will get it from example2.com/myScript.js) and I assumed that the PHP that is on example2.com would not be able to accurately get the client's ip address. – zbee Jul 23 '14 at 14:31
  • Nope, ok, answered my own question I guess. Either way I'm using the same PHP -- Thanks @RobSchmuecker. – zbee Jul 23 '14 at 14:32
  • Any PHP server can have access to the IP for certain. You could even make `www.example2.com/myJavascript.js` a PHP file and spit out the IP variable straight away, that way making it one request rather than 2. But really it depends on what you are trying to do with the IP once you have it from any source? – Rob Schmuecker Jul 23 '14 at 14:34
  • @RobSchmuecker Basically, I'm trying to get a fair bit of info about some clients' users and store it in a central database. So, this JS is getting all the info it can (to avoid issues with including PHP scripts from another website) then sending it all at once to a PHP script on the same server where it will be treated and formatted then put into that database. So, I could make myScript.js just a PHP file (same name, but have PHP in it) and include that as if it were JS, but it'd run normally? – zbee Jul 23 '14 at 14:38
  • 1
    Yes you could. Actually depending on your server setup just make the src a php destination which echoes out javascript. e.g. `` where `myjavascript.php` simply echoes clean javascript. That way you can glean the IP and any other user-specific stuff straight off-the-bat. (Assign the IP as a javascript variable in the `echoe`'d out JS returned by `myjavascript.php`) However if you are submitting any other data to be put into the DB via ajax or form-post etc. you can simply collect the IP address of the user then too! – Rob Schmuecker Jul 23 '14 at 14:43
  • @RobSchmuecker That's awesome! Thanks so much :D But, one of my clients is on a shared hosting server and therefore doesn't have a lot of permissions, would hr be able to include it this way? – zbee Jul 23 '14 at 14:46
  • 1
    Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/57852/discussion-between-rob-schmuecker-and-zbee). – Rob Schmuecker Jul 23 '14 at 14:47