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;)