3

Why the final console log is undefined?Variable time has a global scope and ajax call is async.

This is my code:

var time;
$.ajax({
    async:"false",
    type: 'GET',
    url: "http://www.timeapi.org/utc/now.json",
    success: function(data) {
        console.log(data);  
        time=data;
    },
    error: function(data) {
      console.log("ko");
    }
});
     
console.log(time);  
user229044
  • 232,980
  • 40
  • 330
  • 338
Stefano Maglione
  • 3,946
  • 11
  • 49
  • 96

3 Answers3

5

Change async to the boolean false.

http://api.jquery.com/jQuery.ajax/

var time;
$.ajax({
    async: false,
    type: 'GET',
    url: "http://www.timeapi.org/utc/now.json",
    success: function (data) {
        console.log(data);
        time = data;
    },
    error: function (data) {
        console.log("ko");
    }
});

console.log(time);

Also, note that if you need to use dataType: 'jsonp' here for cross-domain, you won't be able to synchronize -- so use a promise.

var time;
$.ajax({
    dataType: 'jsonp',
    type: 'GET',
    url: "http://www.timeapi.org/utc/now.json",
    success: function (data) {
        time = data;
    },
    error: function (data) {
        console.log("ko");
    }
})
.then(function(){ // use a promise to make sure we synchronize off the jsonp
    console.log(time);    
});

See an example like this here using Q.js:

DEMO

Eric Hotinger
  • 8,957
  • 5
  • 36
  • 43
0

In your code, you initialize the global variable 'time' as 'data'. Where does this data variable come from? If the data variable is not global also, when you try to use console.log(time); , it may be undefined because the data variable is undefined.

Make sure both variables are within scope to be used globally. That might work. Good luck!

  • data is simply the return value of ajax call – Stefano Maglione Aug 09 '13 at 15:05
  • If `data` is a string you are OK. But if your server responds with a JSON object then `data` will be an object, generated for you by jQuery. And the assignment will only *point* to the object. The contents of `data` will *not be copied* into the `time`-variable, but will remain in local scope of the function. – Carsten Massmann Aug 09 '13 at 15:16
0

OK, a bit contrived, but I hope it shows the point regarding scope of time and timing ...

$.ajax({
    async: false,
    dataType: 'jsonp',
    type: 'GET',
    url: "http://www.timeapi.org/utc/now.json",
    success: function (data) {
        console.log(data.dateString);
        time = data.dateString;
    },
    error: function (data) {
        console.log("ko");
    }
});

window.setTimeout("console.log('time: '+time)",3000);

JSfiddle

Carsten Massmann
  • 26,510
  • 2
  • 22
  • 43