views:

178

answers:

3

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.

Edited : Having seen Nick's hint, let me work on it now and see how it goes.

Edited 2nd :

bear with me, still stuck in this:

//ajax load function
function findFromCity(continent, x, y)
{
console.log("clicked on " + continent + ' ' + x + ',' + y);

var cityname = "nowhere";   //variable initialized.

$.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) 
    {
        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);
        }
    }
});

return cityname;  //return after ajax call finished.
} 

Firebug console prints out something interesting :

nowhere
from city found : Sydney

I thought the order should be at least reversed like this :

from city found : Sydney
nowhere

So, basically, the variable defined in success region has a completely different scope from the same variable outside? This sounds bizarre to me at first but now I see it.

Still, don't know how to pass the json object out of the success callback to assign it to another variable...

Conclusion : okay, I got it, working on "pass by reference" to make use of side-effect to change a variable passed in by function parameter now... Which is not directly related to this question.

+1  A: 

Might be a "data" scope problem.

In the second example, which data is which the json object returned, and which one is the one sent?

BenB
@ BenB : the second code snippet is the caller function which calls the "loadRoutes(from_city)" ajax function, and awaits the returning json object from the callee.
Michael Mao
+6  A: 

The success callback occurs when the ajax call completes, so nothing is actually returned by your function, because that statement doesn't run until later.

In the AJAX scenario, you need to get the data object, then call what should run next, because any success or complete callback functions will happen after the code you're running, when the response from the server comes back.

Nick Craver
good point, there is nothing to return there...
BenB
Makes sense....
The Elite Gentleman
@Nick Craver : changing the callback section name from "success" to "complete" in the caller function findFromCity(continent, x, y) would not resolve this problem. data is still recognized as "undefined".
Michael Mao
@Michael Mao - Correct, both of these happen later when the ajax request completes, I was trying to say neither do what you're after here...you need to call whatever you want to run in the success or complete function.
Nick Craver
@Nick Craver : sorry about my dumb head, tried to work out by returning the variable after $.ajax(); is finished, but still got incorrect response.
Michael Mao
And I thought that JQuery Ajax is quite easier. I guess I'll stick to `XMLHttpRequest` object. The Specs are easier to understand.
The Elite Gentleman
@Michael Mao - Might be easier to understand by looking at how the order is happening, in your case it's `$.ajax` (request portion) `return cityname;` (undefined because success hasn't run to set it yet), any other code, then **later** when the server has responded with data, your `success` call is running, that make more sense?
Nick Craver
@The Elite Gentleman - (opinion here) I think they're pretty well laid out and easier to deal with (especially cross-browser), check out the docs for clear explanations: http://api.jquery.com/jQuery.ajax/
Nick Craver
@Nick Craver : Totoally. That explains why. I am now thinking on how to trigger an ajax event when $.ajax(); finishes so I can get the returning value.
Michael Mao
@The Elite Gentleman : I reckon it is me to blame rather than jQuery in this situation :) jQuery ajax call is simple to use, better browser comaptiable just because of dame IE!
Michael Mao
+1  A: 

You could maybe try this method:

function loadRoutes(parameters)
{
    return $.ajax({
        type: "GET",
        async: false,  // This is important... please see ref below

        // Other Settings (don't forget the trailing comma after last setting)

        success: function () {
            console.log('Success');
        },
        error: function () {
            console.log('Error');
        }
    }).responseText;
}

So basically, '.responseText' is added to the '$.ajax' request and the request itself then becomes the return value.

Please note: This usage - returning the result of the call into a variable - requires a synchronous (blocking) request. So use 'async:false' in the settings.

To return a JSON value you could use:

return $.parseJSON($.ajax({
    // Other settings here...
}).responseText);

For more info see: http://api.jquery.com/jQuery.ajax.

Anthony Walsh