简体   繁体   中英

Unable to use callback to get response from ajax call

I'm using the jQuery Validator plugin to try to check whether an email address getting entered into the form is unique after an ajax call which passes the email to a script which checks to see if the email is already in the database. I'm using a callback function to try to get the results of the ajax query but the function always returns undefined. I'm not sure what I'm doing wrong. Here is the code:

jQuery.validator.addMethod("unique", function () {
    function foo(callback) {
        $.ajax({
            type: 'POST',
            async: true,
            url: '/form_processor',
            data: 'action=email_validate&email=' + $("#email").val(),
            success: callback
        });
    }
    var return_value = foo(function (result) {

        if (result !== 'g') {
            return false;
        } else {
            return true;
        }
    });
    alert(return_value);
}, "Email address taken. Choose another.");

If you are using jquery validator, in built method is their to validate, So your validate code will like,

$(document).ready(function(){
   $( "#myform" ).validate({
      rules: {
        email: {
          required: true,
          email: true,
          remote: {
            url: "form_processor",
            type: "post",
            data: {
              email: function() {
                return $( "#email" ).val();
              }
            }
          }
        }
      },
    messages:
         {
         email:
             {
                required: "Please enter your email address.",
                remote: "Email already taken"
             }
         }
    });
})

In server side you have to return (print) true or false code will be (if you are using php)

<?php 
$email =  $_POST['email'];
    $query = "SELECT ID FROM users WHERE user_email = "$email" LIMIT 1;";
    $results = $mysqli->query($query);
    if($results->num_rows == 0)
    {
        echo "true";  //good to register
    }
    else
    {
        echo "false"; //already registered
    }
}
else
{
    echo "false"; //invalid post var
}

?>

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