0
var test = null;

$.get("/zeWebsite.php?blarg=421", function(data){
    test = data.trim();
});

alert(test);

I always thought declaring the variable from outside the function before hand gave access to the variable even if called within the function. However, my test variable is still alerting as null.

Mandar Pande
  • 12,250
  • 16
  • 45
  • 72
derpyderp
  • 323
  • 4
  • 16

3 Answers3

4

It is likely an order issue as the $.get function is asynchronous. The callback of the get is not being run until after the alert has already fired.

The alert is being run BEFORE the get has completed. You need to make sure the get is complete before alerting by triggering alert within the callback.

Try:

var test = null;

$.get("/zeWebsite.php?blarg=421", function(data){
    test = data.trim();
    alert(test);
});

or

var test = null;

$.get("/zeWebsite.php?blarg=421", function(data){
    test = data.trim();
    outside();
});

function outside() { alert(test); }
Carl K
  • 974
  • 7
  • 18
1

it just not assigned yet..
You can simple wait for it:

var test = null, inprocess = true;

$.get("/zeWebsite.php?blarg=421", function(data){
    test = data.trim();
    inprocess = false;
});

var wait = setInterval(function(){
  if (!inprocess) {
    clearInterval(wait);
    alert(test);
  }
}, 500);

But this code is awful. Much better to trigger callback directly:

var test = null;
$.get("/zeWebsite.php?blarg=421", function(data){
    test = data.trim();
    anyactionwithtest(test);
    alert(test);
});

Or use something like jquery deffered promise:

var test = null;
$.get("/zeWebsite.php?blarg=421", function(data){
    test = data.trim();
}).done(function (data){
   // data also accessible here as is
   alert(test);
});
vp_arth
  • 14,461
  • 4
  • 37
  • 66
0

This is because you are using the variable before the get statement execute completely.

Test will get the value when the get function callback call.

If you place alert in get function then it will call at last.