1

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?

johnsnails
  • 1,971
  • 20
  • 29

2 Answers2

2

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.
});
Martin Booth
  • 8,485
  • 31
  • 31
0

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
    }
});
Wilker Iceri
  • 477
  • 2
  • 6