Scope variable in ajax call

ajax, javascript

Solution

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

Problem

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); ```

Original source

Related problems