简体   繁体   中英

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());
     } 

 });
 //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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM