0

Possible Duplicate:
Can’t get correct return value from an jQuery Ajax call
How to return the response from an AJAX call from a function?

I have this:

  get_json = (url) ->
    $.getJSON "#{url}.json", {}, (json, response) ->
      return json

But this compiles to:

getJson = function(url) {
  return $.getJSON("" + url + ".json", {}, function(json, response) {
    return json;
  });
};

..and returns the response object. How can I return just the json instead?

Community
  • 1
  • 1
Damien Roche
  • 13,189
  • 18
  • 68
  • 96
  • 1
    Unlike mentioned questions, this one asks for trouble with coffescript -> js conversion – theadam Jan 17 '13 at 19:37
  • 1
    Is that a joke? The issue is with coffeescript 'returning' $.getJSON. Those other questions do not answer this. – Damien Roche Jan 17 '13 at 19:37
  • Removed jquery tag so people don't get confused. The trouble is that coffeescript is returning the response object by default and I don't know how to prevent that. – Damien Roche Jan 17 '13 at 19:38
  • The problem is exactly the same. AJAX is asynchronous. By the time the server has given the JSON, script execution is already way past that line. – JJJ Jan 17 '13 at 19:40
  • 1
    @Zenph I'm restoring the jQuery tag, as this question is definitely about using jQuery's `$.getJSON` method. – Trevor Burnham Jan 17 '13 at 19:59

1 Answers1

5

A deferred object is being returned, use it to get your data. With your current implementation of the get_json method, this JavaScript should work:

get_json("http://example.com").done(function(obj){
    console.log(obj);
});

your code can be simplified to:

get_json = (url) ->
    $.getJSON "#{url}.json"

There is nothing wrong with the conversion, what's wrong is your assumption of how ajax requests work.

You can't have a function that has a url parameter that sends off an ajax request and returns the data from the function without making the ajax request synchronous (which is a bad idea for various reasons).

Kevin B
  • 94,570
  • 16
  • 163
  • 180