jQuery ajax() returning json object to another function on success causes error
Posted
by Michael Mao
on Stack Overflow
See other posts from Stack Overflow
or by Michael Mao
Published on 2010-03-25T01:32:44Z
Indexed on
2010/03/25
1:43 UTC
Read the original article
Hit count: 578
jQuery
|JavaScript
Hi all:
I got stuck in this problem for an hour. I am thinking this is something relates to variable scoping ? Anyway, here is the code :
function loadRoutes(from_city)
{
$.ajax(
{
url: './ajax/loadRoutes.php',
async : true,
cache : false,
timeout : 10000,
type : "POST",
dataType: 'json',
data :
{
"from_city" : from_city
},
error : function(data)
{
console.log('error occured when trying to load routes');
},
success : function(data)
{
console.log('routes loaded successfully.');
$('#upperright').html(""); //reset upperright box to display nothing.
return data; //this line ruins all
//this section works just fine.
$.each(data.feedback, function(i, route)
{
console.log("route no. :" + i + " to_city : " + route.to_city + " price :" + route.price);
doSomethingHere(i);
});
}
});
}
The for each section works just fine inside the success callback region. I can see Firebug console outputs the route ids with no problem at all.
For decoupling purpose, I reckon it would be better to just return the data object, which in JSON format, to a variable in the caller function, like this:
//ajax load function
function findFromCity(continent, x, y)
{
console.log("clicked on " + continent + ' ' + x + ',' + y);
$.ajax(
{
url: './ajax/findFromCity.php',
async : true,
cache : false,
timeout : 10000,
type : "POST",
dataType : 'json',
data :
{
"continent" : continent,
"x" : x,
"y" : y
},
error : function(data)
{
console.log('error occured when trying to find the from city');
},
success : function(data)
{
var cityname = data.from_city;
//only query database if cityname was found
if(cityname != 'undefined' && cityname != 'nowhere')
{
console.log('from city found : ' + cityname);
data = loadRoutes(cityname);
console.log(data);
}
}
});
}
Then all of a sudden, everything stops working! Firebug console reports data object as "undefined"... hasn't that being assigned by the returning object from the method loadRoutes(cityname)?
Sorry my overall knowledge on javascript is quite limited, so now I am just like a "copycat" to work on my code in an amateur way.
© Stack Overflow or respective owner