7

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?

Andrea
  • 20,253
  • 23
  • 114
  • 183
  • This has been asked many, many times... See for instance: http://stackoverflow.com/questions/31129/how-can-i-return-a-variable-from-a-getjson-function – Shog9 Jan 17 '10 at 17:15

2 Answers2

10

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 );
    });
}
Justin Ethier
  • 131,333
  • 52
  • 229
  • 284
  • This is the cleanest solution so far. I would use as callback a controller method. The drawback is the need to break one controller method into two, but I guess I will use this solution. – Andrea Jan 17 '10 at 17:26
1

Why do you want it to return the object ? If you intend to use this object after, a better way would be to put the function using the data into the callback.

Valentin Rocher
  • 11,667
  • 45
  • 59
  • I said that in the question. The function itself is in a model, and I want to use the object in a controller. Using the object in the callback is doable, but breaks the MVC pattern. Maybe I will do that if i do not find better alternatives. – Andrea Jan 17 '10 at 17:22