1
var dataGraph = new Array();
  $.ajax({
    url:"http://api.fixer.io/2016-01-01",
    dataType: "jsonp",
    success: function(data){
      dataGraph.push(data.rates);
    },
    async: false
  });
  $("#data").html(JSON.stringify(dataGraph));

The array just appear empty even after I try to push data in. There's no error getting the data but it's just not pushing data into the array

Tienanh Nguyen
  • 211
  • 4
  • 9
  • Related: [Why is my variable unaltered after I modify it inside of a function?](http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Jonathan Lonowski Apr 17 '16 at 17:01

1 Answers1

2

Due to the way JSONP requests work, they cannot be made synchronous (and the feature is deprecated on XHR too so you shouldn't use it there either).

Consequently async: false is ignored and the success function is called after the response is received (which is after the the call to html() takes place).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • it's just easier: his url does not return a function but an object – smnbbrv Apr 17 '16 at 16:58
  • @smnbbrv — You must have forgotten to add `callback=something` as a query string (which jQuery will do when you specify it is JSONP) in which case it will return a JavaScript program that makes a function call (i.e. JSONP) . If it didn't do that, then there would be an error, most likely "Unexpected token :", and the question says there is no error. – Quentin Apr 17 '16 at 17:01
  • So basically, if I removed jsonp there would be a cross domain error but for some reason it's just work right now. It is random whether you getting block or not? – Tienanh Nguyen Apr 17 '16 at 17:07
  • @TienanhNguyen — JSONP is a hack to work around the Same Origin Policy. There's nothing random about it. – Quentin Apr 17 '16 at 17:34