简体   繁体   English

无法使用回调获取来自ajax调用的响应

[英]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. 我正在使用jQuery Validator插件尝试检查ajax调用后将表单中输入的电子邮件地址是否唯一,该调用将电子邮件传递给脚本,以检查该电子邮件是否已存在于数据库中。 I'm using a callback function to try to get the results of the ajax query but the function always returns undefined. 我正在使用一个回调函数来尝试获取ajax查询的结果,但该函数始终返回未定义的。 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, 如果您使用的是jQuery Validator,则内置方法将对其进行验证,因此您的验证代码将如下所示:

$(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) 在服务器端,您必须返回(打印) truefalse代码(如果您使用的是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
}

?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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