Page is a not externally linkable
- Code, Content, and Presentation
-- JavaScript and AJAX
---- json headache


Fotiman - 2:34 pm on Feb 20, 2012 (gmt 0)


You're making an AJAX call... the first "A" in AJAX stands for Asynchronous. The anonymous function that you're passing as the last parameter to getJSON is the callback method that will be called at some asynchronous point in the future. So the order of operations in your code might go something like this:


postcodes = $.getJSON(...);
// Asynchronous request send to the server, but no response yet
// postcodes equals nothing useful
console.log(postcodes);
// postcodes still equals nothing useful
return postcodes;
// postcodes still equals nothing useful
// Response comes back from server and anonymous callback function executes


Whatever it is that you need to do with the postcodes returned from the server, you need to put that logic in the callback function. You can't "return" the value because there's nothing to return it to since the request was asynchronous.

Hope that helps.


Thread source:: http://www.webmasterworld.com/javascript/4419536.htm
Brought to you by WebmasterWorld: http://www.webmasterworld.com