Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery: wait for callback before returning

I have a javascript function which asks for some ajax data and gets back a JSON object. Then it should return the object.

The problem is that I don't know how to make the function return from the Ajax callback. Of course

myFunction: function() {
    $.get(myUrl, function(data) {
        return data;
    });
}

does not work, because the inner function is returning instead of the outer.

On the other hand executing what I need just inside the callback will break my MVC subdivision: this code is in a model, and I d'like to use the result object in the controller.

A temporary workaround is

myFunction: function() {
    var result = $.ajax({
        url: myUrl,
        async: true,
        dataType: 'text'
    }).responseText;
    return eval(result);
}

which has the disadvantage of blocking the browser while waiting for the reply (and using eval, which I'd rather avoid).

Are there any other solutions?

like image 922
Andrea Avatar asked Jan 17 '10 17:01

Andrea


1 Answers

You could just pass a callback to your function, to process the data when it is ready:

myFunction: function(callback) {
    $.get(myUrl, function(data) {
        callback( data );
    });
}
like image 73
Justin Ethier Avatar answered Nov 11 '22 21:11

Justin Ethier