Search code examples
javascriptjqueryajaxbackbone.jscoffeescript

How do I update a variable outside an AJAX session? (Backbone JS / CoffeeScript)


For example, I want to update my_data with the session results:

    my_data = []
    url = "/some/endpoint/"

    Session.ajax
        url: url
        type: 'get'
        success: (data) ->
          my_data = data

    console.log JSON.stringify(my_data)
    return my_data

my_data is still empty, so this is definitely not working. What is the correct way of doing this?


Solution

  • That is the correct way.

    my_data is empty because you log it before the request has completed (it is done asynchronously after all).

    You can log (or otherwise use) it inside the success callback.