0
zip = 12345
url = "http://zip.elevenbasetwo.com/v2/US/"+zip; 
res = $.get(url)

When I run above code in the browser console then I can access res.responseJSON but When I run this code in my application.js then I can't access res.responseJSON I am getting undefine.

Does anybody know what's the issue or how can I access in my application.js ?

Dirty-flow
  • 2,306
  • 11
  • 30
  • 49

1 Answers1

1

$.get is asynchronous. The response isn't immediatement available in the jqXHR object.

Pass a success callback to $.get :

$.get(url, function(data){
   // use data
});

The reason why it seems to work in the console is because you don't instantly open the object which is logged : the server answers before. That's not the case in your normal code : while the request is sent, the following line in your code is immediately executed, without waiting for the answer.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758