Bipin Bangwal
Bipin Bangwal

Reputation: 45

Jquery Ajax Boolean Variable is not working well

 $.validator.addMethod("checkUsername", 
   function(value, element){
    var test;     //we want to use this test is like boolean variable
    $.ajax({
        type:"GET",            
        data: 'name='+ value,
        url: "master/ValidationDepartment.jsp",
        success: function(response){  
               test = true;   //assign this value is true                
        },
        error: function() {
               test = false;  //assign this value is false 
    }
    });
         //alert(test);     // bt now this time test value is undifined
    return test;
  }, 
"Departmentname Already Exists."
);
});

I also tried with var test = true. If we declare test = true every time its value is true.

Upvotes: 0

Views: 1586

Answers (2)

AllTooSir
AllTooSir

Reputation: 49372

The .ajax() runs asynchronously and your value will be returned immediately .You can write a callback function in the success or error handler and update the variable . You can set async:false but then it will block till the AJAX response returns.

Upvotes: 0

Kippie
Kippie

Reputation: 3820

Seeing as ajax calls will run asynchronously, the value of test will only change after your function returns. To prevent this from happening, set async: false in the options of your ajax request.

A similar question was asked here: https://stackoverflow.com/a/2982669/1705725

Upvotes: 1

Related Questions