1

Possible Duplicate:
Why is this function returning “undefined”?

Let's assume I have the following JS function:

function getTileData(x, y, loc_slug) {
    $.ajax({
        url: "/sys/map-admin/show-location/"+loc_slug+"/get-tile/"+x+"-"+y+"/",
        success: function(data){
            alert(data); // Object, that's correct.
            **What do I need to make the whole getTileData function return data?**
        }
    });
}

and I call it within another function like

tile = getTileData(1, 2, 'asd');
alert(tile); // undefined
Community
  • 1
  • 1
aemdy
  • 3,702
  • 6
  • 34
  • 49

1 Answers1

0

You can set a async attribute as false ( as default is true ).

Script will be paused until the request is complete.

function getTileData(x, y, loc_slug) {

    var data; // create variable in getTileData scope;
    $.ajax({
        async: false, //
        url: "/sys/map-admin/show-location/"+loc_slug+"/get-tile/"+x+"-"+y+"/",
        success: function( d ){
            data = d; // write ajax result to `data` variable to be available outside this callback;
        }
    });
    return data;
}   
abuduba
  • 4,986
  • 7
  • 26
  • 43