简体   繁体   English

无法获取函数的ajax回调

[英]Can not get ajax callback to a function

I have a form for user to register new account. 我有一个表格供用户注册新帐户。 I use jquery + ajax to check availability of email address on form submission. 我使用jquery + ajax检查表单提交时的电子邮件地址的可用性。 In Jquery code I used e.preventDefault(); 在Jquery代码中,我使用了e.preventDefault(); to prevent form submission if there is any error occurs. 如果发生任何错误,请阻止表单提交。 I tried the existed email address in the email input and click submit the form. 我在电子邮件输入中尝试了现有的电子邮件地址,然后单击“提交表单”。 It allows form to submit. 它允许表单提交。 It should not do this because ajax reponseText return true means that the email address is already existed in database. 它不应该这样做,因为ajax reponseText返回true表示电子邮件地址已经存在于数据库中。

Could anyone please tell me how to fix my code so that if ajax response returns true, it will prevent form submission and shows up errors. 任何人都可以告诉我如何修复我的代码,以便如果ajax响应返回true,它将阻止表单提交并显示错误。

I tried to read and follow this article but fails after so many attempts. 我尝试阅读并遵循这篇文章但经过这么多尝试后失败了。

Here is my form: 这是我的表格:

<form role="form" method="post" id="signupForm" action="index.php?view=signup-gv">
                <div class="col-xs-6 border-right">
                    <div class="form-group">
                        <label for="exampleInputEmail1">Full Name</label>
                        <input type="text" class="form-control" id="regname" name="regname" placeholder="Full Name">
                    </div>
                    <div class="form-group">
                        <label for="exampleInputEmail1">Email Address</label><span id="emailcheck"></span>
                        <input type="email" class="form-control" id="regemail" name="regemail" placeholder="Enter email">
                    </div>
                </div>
                <div class="form-group col-xs-6">
                    <label for="exampleInputPassword1">Password</label>
                    <input type="password" class="form-control" id="regpass" name="regpass" placeholder="Password">
                </div>
                <button style="position:relative; left: 15px; top: 10px;" class="btn btn-default" name="register" id="register">Register</button>
            </form>

Here my jquery code: 这里是我的jquery代码:

$(document).ready(function(){
$('#regname').focus(); 
$('#signupForm').submit(function(e) {
var regname = $('#regname'); 
var regemail = $('#regemail'); 
var regpass = $('#regpass'); 
var register_result = $('#register_result'); 
register_result.html('Loading..'); 
if(regname.val() == ''){ 
    regname.focus();
    register_result.html('<span class="errorss"> * Full name can not be blank</span>');
    e.preventDefault();
}
else if ($.trim(regemail.val()).length == 0) {
    regemail.focus(); 
    register_result.html('<span class="errorss">* Email address can not be blank</span>');
    e.preventDefault();
}
else if(regpass.val() == ''){ 
    regpass.focus();
    register_result.html('<span class="errorss">* Password can not be blank</span>');
    e.preventDefault();
}
emailCheck().done(function(r){
    if(r){
        $('#regemail').focus(); 
        $('#register_result').html('<span class="errorss"> This email address is already existed. Please choose another one </span>');
        e.preventDefault();
        }
    }); 

});
});
function emailCheck() {
var regemail = $('#regemail'); 
var emailcheck = $('#emailcheck');
emailcheck.html(''); 
var UrlToPass = {regemail:regemail.val()} ;
    $.ajax({ 
    type : 'POST',
    cache: false,
    data : UrlToPass,
    url  : 'emailcheck.php',
    success: function(responseText){ 
        if(responseText == 0){
            return false; // good to go
        }
        else{
            emailcheck.html('<span class="errorss"> This email is existed.</span>');
            return true; // This email is registered. Please try different one
        }
    }
    });

} }

You are confusing yourself with sync and async functions. 您对同步和异步功能感到困惑。 An ajax function makes an Async call and returns output in its callback. ajax函数进行异步调用并在其回调中返回输出。 You are trying to wrap an Async function inside a normal function and expecting it to behave synchronously. 您正在尝试将Async函数包装在普通函数中并期望它同步运行。

Your function returns before the Ajax call receives its output. 您的函数在Ajax调用收到其输出之前返回。 Use 采用

async: false async:false

$.ajax({ 
    type : 'POST',
    cache: false,
     async: false,
    data : UrlToPass,

Refer to following for dettails: 请参阅以下内容:

How to make JQuery-AJAX request synchronous 如何使JQuery-AJAX请求同步

First you are not returning anything from the emailCheck() function, but you are using it as if it is returning a promise object. 首先,您没有从emailCheck()函数返回任何内容,但是您正在使用它,就像它返回一个promise对象一样。

So 所以

$(document).ready(function () {
    $('#regname').focus();
    $('#signupForm').submit(function (e) {
        var regname = $('#regname');
        var regemail = $('#regemail');
        var regpass = $('#regpass');
        var register_result = $('#register_result');
        register_result.html('Loading..');
        //prevent the form submit
        e.preventDefault();

        if (regname.val() == '') {
            regname.focus();
            register_result.html('<span class="errorss"> * Full name can not be blank</span>');
        } else if ($.trim(regemail.val()).length == 0) {
            regemail.focus();
            register_result.html('<span class="errorss">* Email address can not be blank</span>');
        } else if (regpass.val() == '') {
            regpass.focus();
            register_result.html('<span class="errorss">* Password can not be blank</span>');
        } else {
            emailCheck().done(function (r) {
                if (r) {
                    $('#regemail').focus();
                    $('#register_result').html('<span class="errorss"> This email address is already existed. Please choose another one </span>');
                } else {
                    $('#signupForm')[0].submit();
                }
            });
        }
    });
});

function emailCheck() {
    var regemail = $('#regemail');
    var emailcheck = $('#emailcheck');
    emailcheck.html('');
    var UrlToPass = {
        regemail: regemail.val()
    };
    var deferred = jQuery.Deferred();
    $.ajax({
        type: 'POST',
        cache: false,
        data: UrlToPass,
        url: 'emailcheck.php',
        success: function (responseText) {
            if (responseText == 0) {
                deferred.resolve(false);
            } else {
                emailcheck.html('<span class="errorss"> This email is existed.</span>');
                deferred.resolve(true);
            }
        },
        error: function () {
            deferred.reject();
        }
    });
    return deferred.promise();
}

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

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