Is there some way I can fix this so that I can get the variables outside the scope within the microAjax function?
I want latlng to take on the value of ipaddress outside microAjax.
var latlng = microAjax("php/latlng.php", function(ipaddress) {
console.log(ipaddress);
return ipaddress;
});
console.log(latlng);
I’ve tried something like this also:
var lat;
var lng;
microAjax("php/latlng.php", function(ipaddress) {
var arrayOfLocation = ipaddress.split(" ");
lat = parseFloat(arrayOfLocation[0]);
lng = parseFloat(arrayOfLocation[1]);
console.log(ipaddress);
});
console.log(lat);
console.log(lng);
But in both cases the variables outside the function are undefined. How do I get variables to be defined from microAjax, but outside its scope?
Your problem is the asynchronous call, not the scope.
the ajax is finished after you output lat and lng in the second example.
within jquery ajax the parameter async fixes that.
http://api.jquery.com/jQuery.ajax/
(if you are using jquery)