0

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?

Stagleton
  • 1,060
  • 3
  • 11
  • 35
  • 7
    The ajax is asynchronous, that's why you're getting undefined. – David G Jan 28 '13 at 18:50
  • 1
    We need to petition ECMA to rename `JavaScript` to `AsynchronousScript` so people stop posting this same question on StackOverflow 400 times a day. – Mike Christensen Jan 28 '13 at 18:52
  • 1
    Take your pick of duplicates: [this one](http://stackoverflow.com/questions/2813974/javascript-ajax-function-returns-undefined-instead-of-true-false), [or this one](http://stackoverflow.com/questions/3485782/jquery-ajax-returns-undefined), [or this one](http://stackoverflow.com/questions/6776719/ajax-request-returns-undefined-result), [or this one](http://stackoverflow.com/questions/7703390/ajax-function-returning-undefined), [or this one](http://stackoverflow.com/questions/5656490/why-this-javascript-method-return-undefined)... out of characters. – jbabey Jan 28 '13 at 19:09

1 Answers1

1

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)

scones
  • 3,317
  • 23
  • 34