views:

49

answers:

2

I stripped all my logic out of my jquery plugin for this question, but my problem is that when I call my function checkValidationName, it does it's thing and sets name = to true. Then when i try to compare it right after where i called it, the value is false. Why is this?

 (function($){  
       $.fn.validate = function() {     

            var name = false;

            $('.submitBtn').click(function() {


                 $.fn.validate.checkValidationName(nameValues);


                 **console.log("name = "+name); **//but this prints out "false"****
                 //shouldn't this be true since name returned true in the actual function??


                 }
            });

            $.fn.validate.checkValidationName = function(id) {
                 $.post("PHP/submitButtonName.php", {checkValidation: id},
                     function(data) {

                          **console.log("name = "+name); **//this prints out "true"**** 
                          //name is equal to true here

                     }, "json");
            };

      }    
 })(jQuery);  
+1  A: 

It's because the call to $.post() in checkValidationName is asynchronous. When you invoke the following line...

$.fn.validate.checkValidationName(nameValues);

Execution continues to the next line almost right away -- long before you get a result fro $.post(), at any rate.

Drew Wills
I tried doing $.ajax with type "POST" and setting async: false rather than $.post and that still didn't work.
Catfish
+1  A: 

That's because the AJAX requests are asynchronous and right after you called checkValidationName, it hasn't finished yet. You need to do the comparison in the callback.

You can make checkValidationName take a callback and call it with the result when validated:

(function($){
    $('.submitBtn').click(function() {
        $.fn.validate.checkValidationName(nameValues, function(valid) {
            console.log(valid);
        });
    });

    $.fn.validate.checkValidationName = function(id, callback) {
         $.post("PHP/submitButtonName.php", {checkValidation: id},
             function(data) {
                var valid = data.foo; // or however you determine that

                callback(valid); // call callback
             }, "json");
    };
}(jQuery));
jou
Is there a way to keep the value of name and use it in a different function? I have 3 functions similar to checkValidationName all using different variables and I want to compare all of the variables and perform an operation if all 3 pass are valid, not just one.
Catfish
You can do something like http://pastie.org/817909.If you need to do something if not everything is valid, you need to keep track of how many times doStuffIfAllValid() has been called.
jou