开发者

jquery function doesn't return values correctly

I have this function

$.fn.validate.checkValidationName = function(id) {
 $.post("PHP/submitButtonName.php", {checkValidation: id},
     function(data) {
  if(data.returnValue === true) {
         name = true;
  } else {
      name = false;
  } 
  **console.log("name = "+name); **//this prints out "true"****  
 }, "json");
};

and this .click function that calls it. All the variables are declared outside this function so that they should be accessible by other functions

$('.submitBtn').click(function() {
 //clears the array before re-submitting the click function
 nameValues = [];
 usernameValues = [];
 emailValues = [];
 name = false;
 username = false;
 email = false;

 //for each of the input tags
 $("input").each(function() {

        //if the curent input tag has the class .name, .userpass, or .email
     if(($(this).hasClass("name"))) {
         nameValues.push($(this).val());
     } else if(($(this).hasClass("userpass"))) {
      usernameValues.push($(this).val());
     } else if(($(this).hasClass("email"))) {
      emailValues.push($(this).val());
     } 

 });开发者_JS百科
 //call the checkValidation function with the array "values"
 $.fn.validate.checkValidationName(nameValues);
 $.fn.validate.checkValidationUsername(usernameValues);
 $.fn.validate.checkValidationEmail(emailValues);

 console.log("name = "+name); //but this prints out "false"
 console.log("username = "+username);
 console.log("email = "+email);

 if((name === "true") && (username === "true") && (email === "true")) {
     alert("Everything checks out great"); 
 } else {
     alert("You missed one!"); 
 }
});

When I click the link to trigger the first function, it returns the value as "true" inside the function, but when I console.log("name"+name); in the .click function after the function call, it prints out false.

Why is this? Do I need to return something from the checkValidatoinName function?


$.post is asynchronous, which means that it won't wait for the result to get back before proceeding. You're probably initializing name to true somewhere, and it's getting true the first time, but all the other times, it's false, because the AJAX from the first one finished and set it to false.

Try using $.ajax instead of $.post, and set async to false in the options. The $.post documentation shows the options that $.post would give to $.ajax.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜