javascript 使用 JQuery Ajax 进行电子邮件验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20381476/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 18:22:29  来源:igfitidea点击:

Email validation using JQuery Ajax

javascriptphpjqueryajaxemail

提问by Sebastian

I've been having a hard time trying to validate an email with ajax using PHP and Javascript. What I want to do, is to check if the email already exists in the database, if so, display a message and then go back to the form, otherwise display a success message and close the form. The problem is that if the email exists it is displaying the "error message" and then displays the success message. I've checked similar questions and tried the code in them but none of them applied correctly to my requirements. Thank you.

我一直在尝试使用 PHP 和 Javascript 通过 ajax 验证电子邮件时遇到了困难。我想要做的是检查该电子邮件是否已存在于数据库中,如果存在,则显示一条消息然后返回表单,否则显示一条成功消息并关闭该表单。问题是,如果电子邮件存在,它会显示“错误消息”,然后显示成功消息。我检查了类似的问题并尝试了其中的代码,但没有一个能正确地满足我的要求。谢谢你。

Here's what I've got:

这是我所拥有的:

// JavaScript Document
$('#btnSubmit').click(function(){
    if(  validateForm() ){
        // code to submit all the info, display the success message and close the form
    }
    else return false;
});


// I created a function to validate all the fields in the form
function validateForm() {
    var firstName = $('#txtFirstName').val();
    var lastName = $('#txtLastName').val();
    var email = $('#txtMail').val();

    // to validate firstName and lastName I do it like this:
    if(!firstName || firstName.length === 0) {
        message = "All fields are mandatory\nFirst Name is required";
        messageDialog("Warning", message, "warning", 2);
        return false;
    } 
    if( !firstName.match(letters) ) {
        message = "Invalid name";
        messageDialog("Warning", message, "warning", 2);
        return false;
    }
    // So far, no problem at all. But when I tried to validate email:
    else {
        // use ajax to check if a user has been previously registered
        // using this email
        $.ajax({
            url:"check_user.php",   // url that will use
            data:{                  // data that will be sent
                email:email
            },
            type:"POST",            // type of submision
            dataType:"text",        // what type of data we'll get back
            success:function(data)
            {    
                // if check_user returns a number different than 0
                // means that there's already a user registered with that email
                if(data > 0 ) {
                    message = "This email is registered already!";
                    messageDialog("Error", message, "error", 2);
                    return false;                   
                 }
                 else { return true;}
            }
        });

    }

    // if everything is right then return true so the submit function continue its execution
    return true;
}

采纳答案by brian

You perform an ajax request, which by default is asynchronous, which means it doesn't wait for the response of your request before doing the rest of your function.

您执行一个 ajax 请求,默认情况下它是异步的,这意味着它不会在执行其余功能之前等待您的请求的响应。

So in your case, once the request is made, it will return trueas stated as the end of your function. Then, when the response of your ajax request comes back, it will trigger your successfunction, which will display the error message.

因此,在您的情况下,一旦发出请求,它将true按照您的函数结束的说明返回。然后,当您的 ajax 请求的响应回来时,它会触发您的success函数,该函数将显示错误消息。

You can do something like that, using the asyncparameter of the $.ajaxfunction to make sure that it will wait for the response of your request before going any further.

您可以执行类似的操作,使用函数的async参数$.ajax来确保它在继续之前等待您的请求的响应。

function validateForm() {
    var firstName = $('#txtFirstName').val();
    var lastName = $('#txtLastName').val();
    var email = $('#txtMail').val();

    // to validate firstName and lastName I do it like this:
    if(!firstName || firstName.length === 0) {
        message = "All fields are mandatory\nFirst Name is required";
        messageDialog("Warning", message, "warning", 2);
        return false;
    } 
    if( !firstName.match(letters) ) {
        message = "Invalid name";
        messageDialog("Warning", message, "warning", 2);
        return false;
    }
    // So far, no problem at all. But when I tried to validate email:
    else {
        // use ajax to check if a user has been previously registered
        // using this email
        var valid = false;
        $.ajax({
            url:"check_user.php",
            async: false,
            data:{                  // data that will be sent
                email:email
            },
            type:"POST",            // type of submision
            dataType:"text",        // what type of data we'll get back
            success:function(data)
            {    
                // if check_user returns a number different than 0
                // means that there's already a user registered with that email
                if(data == 0 ) {
                    valid = true;
                }
            }
        });
        if(!valid) {
             message = "This email is registered already!";
             messageDialog("Error", message, "error", 2);
             return false;
        } else { return true; }
    }
    }

回答by Lamari Alaa

In Ajax call the success function is async that means your function will return always true if it arrive to check your email.

在 Ajax 调用中,成功函数是异步的,这意味着如果它到达检查您的电子邮件,您的函数将始终返回 true。

to correct this, you have to remove return true from your last else and inside success function call a function that will close your form like this :

要纠正此问题,您必须从最后一个 else 和内部成功函数中删除 return true 调用一个函数,该函数将关闭您的表单,如下所示:

// JavaScript Document
$('#btnSubmit').click(function(){
    if(  validateForm() ){
        // code to submit all the info, display the success message and close the form
    }
    else return false;
});


// I created a function to validate all the fields in the form
function validateForm() {
    var firstName = $('#txtFirstName').val();
    var lastName = $('#txtLastName').val();
    var email = $('#txtMail').val();

    // to validate firstName and lastName I do it like this:
    if(!firstName || firstName.length === 0) {
        message = "All fields are mandatory\nFirst Name is required";
        messageDialog("Warning", message, "warning", 2);
        return false;
    } 
    if( !firstName.match(letters) ) {
        message = "Invalid name";
        messageDialog("Warning", message, "warning", 2);
        return false;
    }
    // So far, no problem at all. But when I tried to validate email:
    else {
        // use ajax to check if a user has been previously registered
        // using this email
        $.ajax({
            url:"check_user.php",   // url that will use
            data:{                  // data that will be sent
                email:email
            },
            type:"POST",            // type of submision
            dataType:"text",        // what type of data we'll get back
            success:function(data)
            {    
                // if check_user returns a number different than 0
                // means that there's already a user registered with that email
                if(data > 0 ) {
                    message = "This email is registered already!";
                    messageDialog("Error", message, "error", 2);
                    return false;                   

                 } else {
                   // code to submit all the info, display the success message and close the form
                 yourfunctiontocloseyourform()
                 }
            }
        });
        return false;

    }

}

回答by jeroen

I don't see any success message, but I assume that your validate()function returns truewhen the e-mail address already exists.

我没有看到任何成功消息,但我假设您的validate()函数true在电子邮件地址已经存在时返回。

This is caused by the fact that your ajax call is asynchronous and is not yet finished when your validate()function finishes. Apart from that what your return from your anonymous successfunction, is not what is returned from your ajax call; you don't even use the return value from your ajax call.

这是由于您的 ajax 调用是异步的,并且在您的validate()函数完成时尚未完成。除此之外,您从匿名success函数返回的内容不是从 ajax 调用返回的内容;您甚至不使用 ajax 调用的返回值。

You can either make your ajax call synchronous and use a variable to set the return value from it or you can return the return value of your ajax call as well and continue processing when the ajax call is finished.

您可以使您的 ajax 调用同步并使用一个变量来设置它的返回值,或者您也可以返回 ajax 调用的返回值并在 ajax 调用完成后继续处理。