Sash
Sash

Reputation: 493

jQuery Ajax response and variable assignment problem

I have the following code inside $(document).ready block:

$.ajax({
    type: "POST",
    url: "Test.aspx/CheckType",
    data: "{}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (response) {
        if (response.d == true) {
            user = true;   
        }
        else {
            user = false;   
        }
    },
    error: function () {
        alert("ERROR");  
    }
});


if (user) {
    // code that doesn't execute
}
else {
    // code that always executes!!
}

The problem is that user variable is undefined and always executes the code inside the else block.

I checked with FireBug that the ajax call is successful.

What can be the problem?

Thanks in advance!!!

Upvotes: 0

Views: 582

Answers (1)

8vius
8vius

Reputation: 5836

It's most likely a problem with the user variable being read before the ajax call is returned so it will always be undefined, try placing your if statement inside the ajax call and test it that way.

Upvotes: 1

Related Questions