I have the following code.
var dat = null;
$.get("example.com", function(data){
dat = data;
alert(dat); // Has the info.
});
alert(dat); // null.
How can I access dat
outside $.get
?
I have the following code.
var dat = null;
$.get("example.com", function(data){
dat = data;
alert(dat); // Has the info.
});
alert(dat); // null.
How can I access dat
outside $.get
?
Accessing that variable should work fine. The problem is that the function which sets dat will run after the last alert.
The function is a callback.. it only runs after get has complete, whereas the last alert will run straight away.
Here is a way to chain code after the callback
var dat = null;
$.get("example.com", function(data){
dat = data;
alert(dat); // Has the info.
}).then(function() {
alert(dat); // Has the info too.
});
The line alert(data); is executed before the $.get() because the async. Use the $.ajax() with async:false or put alert(data) in success of $.get():
$.ajax({
type: "GET",
async: false,
url: "example.com",
success: function(data) {
dat = data;
alert(dat);
},
error: function(e) {
console.log(e); //error
}
});