0

I have javascript code similar to the following, however when I try to use 'myVar' within foo(), its value is undefined. I've also tried passing the variable into bar() and assigning it directly, but will not pass by reference.

function foo() { 
   bar();
   var myVar = document.getElementById('coords').value;
   // myVar should now be (40.7143528, -74.0059731)
   alert(myVar); // returns blank

   var request = {
    location: myVar,
    radius: 500,
    types: [type] //previously defined 
   };

   //Then send a search request to Google...
}

function bar() {
   geocoder.geocode( {'address':address}, function(results, status) {

      document.getElementById('coords').value = results[0].geometry.location;
      // Let's say the location is NYC (40.7143528, -74.0059731)

     alert(document.getElementById('coords').value); //returns the correct value
     // however, this pops up after the pop up in function foo() 

   });
}

with the following HTML

<input type="hidden" id="coords" name="coords"/>

The real code is using Google Maps API if that makes a difference:

7
  • When do you call foo? Commented Apr 1, 2013 at 22:59
  • Also, when I placed debug alerts, it seems as if the creation of 'myVar' occurs before bar() is called. Commented Apr 1, 2013 at 22:59
  • foo() is called onClick on a button (before the hidden variable in the HTML) Commented Apr 1, 2013 at 23:01
  • When are you trying to access myVar? Commented Apr 1, 2013 at 23:02
  • Trying to access myVar (or at least the value placed into the hidden variable 'coords') a few lines down in foo() Commented Apr 1, 2013 at 23:13

2 Answers 2

1

bar runs asynchronously because geocoder does. That means that

document.getElementById('coords').value = results[0].geometry.location;

actually executes after

var myVar = document.getElementById('coords').value;

You can't use ajax this way. All of your work that relies on results/status has to be done in the callback.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. What I ended up doing was just putting bar() inside foo(), instead of having it as an additional function. I would've liked to have the separate function, but I will likely not need it.
1

jsfiddle Demo

Runs fine for me. Make sure when defining your functions to actually use function in front of the definition.

function foo() { 
 bar();
 var myVar = document.getElementById('coords').value;
}

function bar() {
 document.getElementById('coords').value = 4;
}

foo();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.