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?
Ajax is asynchronous so response will not be set when you call
console.log response, use response in the callback function.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