1

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?

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

3 Comments

Ok, so 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.
Use async: false solves everything in this particular situation. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.