mat-mcloughlin
mat-mcloughlin

Reputation: 6722

Return Results of Ajax Request in Coffeescript

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

Upvotes: 1

Views: 5484

Answers (2)

Marius Kjeldahl
Marius Kjeldahl

Reputation: 6824

As mentioned already, this has to do with the async nature javascript in the browser. There's "a patch" to CoffeeScript that deals with this directly (adding async/defer), see http://maxtaco.github.com/coffee-script/ . For your example, it would be something like (guesswork on my side based on my understanding of it):

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

There are numerous other javascript libraries as well which can also be used for similar purposes. But be aware that the browser may appear "hung" while your script is waiting for data (not sure if the "defer" function keep handling javascript events or not).

Upvotes: 0

Sandro
Sandro

Reputation: 4771

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.

Upvotes: 5

Related Questions