-1

I've been trying to get my global variable's value to change upon running a function test(), but it doesn't seem to work and I have no idea why. I've tried declaring the variable outside the $(document).ready jQuery code and I've also tried using window.testvar to no avail. What could I be missing here, and how would I go about fixing this so the AJAX success function changes the value of testvar?

$(document).ready(function() {
    testvar = '';

    function test() {
        $.ajax({
            type: 'POST',
            url: 'test.php',
            data: { sessionUsername: $sessionUsername },
            dataType: 'json',
            success: function (data) {
                testvar = '1';
                console.log(testvar);
            }
        })
    }

    test(); // logs '1'

    console.log(testvar); // logs nothing
};

1 Answers1

2

Your console.log runs before the ajax succes function is executed..

You see, the ajax function is an asynchronous function, which means it runs out of the block sequence you are calling the function in.

Jimmy Knoot
  • 2,378
  • 20
  • 29