Reputation: 43123
I'm using CoffeeScript and jQuery, trying to get the data from an ajax call stored in a local variable so I can use it in the rest of my method. Here's my existing code:
response = null
$.ajax
url: '/polygons'
dataType: 'json'
success: (data, textStatus, jqHXR) ->
response = data
console.log response
With this code, response always stays null. All I want to do is get the data variable out of the success function and into the calling method, but I can't seem to get it out of that scope. What am I doing wrong here?
Upvotes: 1
Views: 1811
Reputation: 97672
Ajax is asynchronous so response will not be set when you call console.log response
, use response in the callback function.
response = null
$.ajax
url: '/polygons'
dataType: 'json'
success: (data, textStatus, jqHXR) ->
response = data
console.log response
how do I make sure the script waits after this until the ajax call is complete, so it won't proceed using the null response object?
You should just do all your processing in the callback function, if you don't want to do that you can make the ajax call synchronous by changing async to false in the ajax options
Upvotes: 4