0

I have a form for user to register new account. I use jquery + ajax to check availability of email address on form submission. In Jquery code I used 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.

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.

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:

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

}

Giang Nguyen
  • 495
  • 8
  • 22

2 Answers2

0

You are confusing yourself with sync and async functions. An ajax function makes an Async call and returns output in its callback. You are trying to wrap an Async function inside a normal function and expecting it to behave synchronously.

Your function returns before the Ajax call receives its output. Use

async: false

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

Refer to following for dettails:

How to make JQuery-AJAX request synchronous

Community
  • 1
  • 1
adnan kamili
  • 8,967
  • 7
  • 65
  • 125
  • i understood async and sync. Thats why i tried solution from this article: https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call. But techniquely, i dont know what i did was correct or not? So if you find it a stupid error, please point it out and please how to fix it for my case. thank you very much – Giang Nguyen Feb 26 '15 at 06:30
0

First you are not returning anything from the emailCheck() function, but you are using it as if it is returning a promise object.

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();
}
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531