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?

5
  • 1
    Unlike mentioned questions, this one asks for trouble with coffescript -> js conversion Commented Jan 17, 2013 at 19:37
  • 1
    Is that a joke? The issue is with coffeescript 'returning' $.getJSON. Those other questions do not answer this. Commented Jan 17, 2013 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. Commented Jan 17, 2013 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. Commented Jan 17, 2013 at 19:40
  • 1
    @Zenph I'm restoring the jQuery tag, as this question is definitely about using jQuery's $.getJSON method. Commented Jan 17, 2013 at 19:59

1 Answer 1

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).

Sign up to request clarification or add additional context in comments.

2 Comments

Got it thanks. Got some studying to do :)
I guess in a way coffee script did the right thing by returning the response, :-p