Ajax – Return Results of Ajax Request in Coffeescript

ajaxcoffeescript

Still getting my head around CoffeeScript and and seeing what its capable of.

I've written a method that makes a ajax call and I'm wanting to return the results.

For example:

GetViewedItem: (foo) ->
    $.ajax '/Foo/Bar/',
    type: 'GET',
    data: { id: $(foo).data('fooId') }
    success: (data) ->
        data

and I want to return data. Is there a clever way of doing this in CoffeeScript or do I just have to declare a variable?

Thanks

Best Answer

You can't really return the data on an AJAX request that way since it is asynchronous. Meaning, by the time the success callback is called, your GetViewedItem method will have finished executing.

Normally, you would continue doing whatever you need to do with the AJAX data in the success callback or call a method from the success callback that deals with the data accordingly.

handleViewedItem: (data) ->
    // Do something now that the AJAX call is complete.

GetViewedItem: (foo) ->
    $.ajax '/Foo/Bar/',
        type: 'GET',
        data: { id: $(foo).data('fooId') }
        success: (data) ->
            handleViewedItem data

This is probably one of the most important concepts to understand when using JS and AJAX.