3
var doCheck = function() {
    var data;

    $.ajax({
        url: 'check.php',
        data: 'ch=check',
        success: function(resp) {
            data = resp;
        }
    });
console.log(data);
    return data == 1;
};

The above code, regardless of the data only ever returns a 0 or a 1. Within the scope of the success callback, this is true. The argument resp has a value of 0 or 1 depending on input.

However, whenever I try to access a private variable (should not be affected by scope), nothing happens; and when console.log(data); is called all that is written to the console is undefined.

This function has no parent, so don't worry about some other kind of scope interference.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Nahydrin
  • 13,197
  • 12
  • 59
  • 101
  • 2
    You will always log data before the ajax call has been made, hence data will be undefined. – Johan Feb 22 '12 at 18:10

5 Answers5

3

Ajax is asynchronous. Which is why you have to organize your logic with callbacks:

var doCheck = function(callback) {
    var data;

    $.ajax({
        url: 'check.php',
        data: 'ch=check',
        success: function(resp) {
            callback(data == 1);
        }
    });
};

doCheck(function(result) {
    // result is true or false
});
Daff
  • 43,734
  • 9
  • 106
  • 120
  • I forgot the call was asynchronous. Your solution let me maintain an async callback and send data back, thanks. – Nahydrin Feb 22 '12 at 18:53
2

Place the 'console.log(data)' sentence after 'data=resp'. Probably it is executing before the success method and becuase this it has no value set.

acanimal
  • 4,800
  • 3
  • 32
  • 41
2

It takes time till you get the response, so the console.log() comes when the data isn't set yet

Neysor
  • 3,893
  • 11
  • 34
  • 66
0

This is because the ajax Request by default is asynchronous, however instead of making it synchronous, I'd suggest redesigning you're approach.

SSH This
  • 1,864
  • 4
  • 23
  • 41
0

Ajax stands for Asynchronous JavaScript and XML. data is being set after the call to the server returns, and only if the call was sucessfull.

The console.log is happening immediatly after sending the async request off, before the sucess has a chance to run.

asawyer
  • 17,642
  • 8
  • 59
  • 87