galingong galingong - 2 months ago 9
Ajax Question

Global variable accessed inside pre-defined function returns null - javascript

For some reason, I can't access a variable. Might be a scope issue, or timing issue, can't find it out. Here's my simplified code:

var endResult = "";

//function loads html into given element.Called as a callback later when google maps direction service is done//
function getResults(){
data: endResult,
//etc., response loaded asynchronously in div element//

//when form is submitted
var endResult = "";
//get form data, define variable//
var location = data;
//initialize Maps Directions Service//
var directionService = new google.maps.DirectionsService();
//function gets directions, and loads a single value into global variable "endResult"//
function calcRoute(){
var request = {//google maps arguments containing form data//};
directionsService.route(request, function(result, status) {
var endResult = JSON.stringify(result.routes[0].legs[0].distance.value);
console.log(endResult); //Outputs intended value from google maps//
//run function as a callback making sure that "endResult" is not null//
getResults(); //iside this function - value of "endResult" is null, data sent to foo.php is null//
return false;

That's it, once I call getResults(), inside that function, endResult will be null. I'm sure it's something simple, but I can't get my head around it.

Answer Source

You're not assigning to the global variable, because you have

    var endResult = "";
//  ^^^

in the submit handler, and

    var endResult = JSON.stringify(result.routes[0].legs[0].distance.value);
//  ^^^ calcRoute.

Those declare local variables in those functions, which shadow the global (and the one in calcRoute shadows the one in the submit handler).

Just remove those vars, so you're assigning to the variable that code closes over (the global).

In general, avoid using truly global variables, and minimize the degree to which functions have side effects (like assigning to and reading from variables they close over). In this case, rather than having endResult be a global, there's no reason calcRoute can't pass it to getResults as an argument.