0

Hi guys please help me to solve my problem. Actually i am trying to validate my email field on form using javascript and post an ajax request to check if that email exists or not but my javascript function does not wait until the ajax response and every time it returns false. I want to be return true when email does not exist...

    $(document).ready(function(){
    //global vars
    var form = $("#signupForm");
    var email = $("#email");
    var email_error = $("#invalid");

    //On blur
   // userEmail.blur(validateEmail);

    //On Submitting
    form.submit(function(){

        if(validateEmail()){
            alert("submit true");
            return true;
        }else{
        alert("submit false");
            return false;
            }
    });


    function validateEmail(){
        //if it's NOT valid
        alert("In email");
        var a = $("#email").val();
        var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+@[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;

        if(email.val() == ""){
            email_error.html("Please enter your email ");
            return false;
        }
        //if it's valid email
        else if(filter.test(a)==false){
            email_error.html("Please enter Valid email address");
            return false;
        }
        else if(filter.test(a)==true){alert("elseif");
        var baseUrl = '<?= base_url() ?>';

                $.ajax({
                    type: "POST",
                    url: baseUrl+"index.php/index/validateUserEmail",
                    data: "useremail="+$("#email").val(),
                    success: function(msg){
                    alert(msg);
                    if(msg == "1")
                        {
                            $("#tick_cross").fadeIn("slow").html('<img src="'+baseUrl+'images/cross.png" />');
                            $("#emailValidate").val("1");  
                            email_error.html("This email-Id already exists!");
                            return false;
                        }
                        else
                        {

                            $("#tick_cross").fadeIn("slow").html('<img src="'+baseUrl+'images/tick.png" />');
                            $("#emailValidate").val("0");
                            email_error.html(" ");
                            alert("alok");
                            return true;
                        }


                    }
                });

        }

        else{
        email_error.html(" ");
        return true;
        }

    }
});
Pete
  • 57,112
  • 28
  • 117
  • 166
  • it will not work like that because of async nature of ajax, you need to use a callback to solve it – Arun P Johny Mar 20 '13 at 11:48
  • Try setting the option async : false as in here: http://stackoverflow.com/questions/133310/how-can-i-get-jquery-to-perform-a-synchronous-rather-than-asynchronous-ajax-re – Captain Payalytic Mar 20 '13 at 11:49
  • FYI, `async` is deprecated post `v1.8` – asprin Mar 20 '13 at 11:53
  • thanks for reply arun but how i use it here ...?? – Salman Ahmad - Mean Developer Mar 20 '13 at 11:54
  • Comment turned back to answer because that is what it is, an answer! – Captain Payalytic Mar 20 '13 at 11:57
  • You need to set the option async : false as in http://stackoverflow.com/questions/133310/how-can-i-get-jquery-to-perform-a-synchronous-rather-than-asynchronous-ajax-re – Captain Payalytic Mar 20 '13 at 11:59
  • As Arun said, there is no need to manipulate the sync param, Ajax is async and that the basic and good behaviour (if you are using sync request, the browser will freeze waiting for response...Bad!). When the user submit the form, you run your ajax call and return directly false to stop the propagation of the event and prevent the default behaviour (in this case, a submit). Later, when the AJAX response comme back, if the email is good, submit the form by the code (which will not run again the check). That's all. – MatRt Mar 20 '13 at 11:59

4 Answers4

1

Try something like

$(document).ready(function() {
    // global vars
    var form = $("#signupForm");
    var email = $("#email");
    var email_error = $("#invalid");

    // On blur
    // userEmail.blur(validateEmail);

    // On Submitting
    form.submit(function() {

                validateEmail(function(flag) {
                            if (flag) {
                                alert("submit true");
                                form[0].submit();
                            } else {
                                alert("submit false");
                            }

                        });
                return false;
            });

    function validateEmail(callback) {
        // if it's NOT valid
        alert("In email");
        var a = $("#email").val();
        var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+@[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;

        if (email.val() == "") {
            email_error.html("Please enter your email ");
            callback(false);
        }
        // if it's valid email
        else if (filter.test(a) == false) {
            email_error.html("Please enter Valid email address");
            callback(false);
        } else if (filter.test(a) == true) {
            alert("elseif");
            var baseUrl = '<?= base_url() ?>';

            $.ajax({
                        type : "POST",
                        url : baseUrl + "index.php/index/validateUserEmail",
                        data : "useremail=" + $("#email").val(),
                        success : function(msg) {
                            alert(msg);
                            if (msg == "1") {
                                $("#tick_cross").fadeIn("slow")
                                        .html('<img src="' + baseUrl
                                                + 'images/cross.png" />');
                                $("#emailValidate").val("1");
                                email_error
                                        .html("This email-Id already exists!");
                                callback(false);
                            } else {

                                $("#tick_cross").fadeIn("slow")
                                        .html('<img src="' + baseUrl
                                                + 'images/tick.png" />');
                                $("#emailValidate").val("0");
                                email_error.html(" ");
                                alert("alok");
                                callback(true);
                            }

                        }
                    });

        }

        else {
            email_error.html(" ");
            callback(true);
        }

    }
});

Demo: Fiddle

Or better solution with jQuery.deferred

$(document).ready(function() {
    // global vars
    var form = $("#signupForm");
    var email = $("#email");
    var email_error = $("#invalid");

    // On blur
    // userEmail.blur(validateEmail);

    // On Submitting
    form.submit(function() {
                validateEmail().done(function() {
                            console.log("submit true");
                            form[0].submit();
                        }).fail(function() {
                            console.log("submit false");
                        });
                return false;
            });

    function validateEmail() {
        var deferred = jQuery.Deferred()

        // if it's NOT valid
        console.log("In email");
        var a = $("#email").val();
        var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+@[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;

        if (email.val() == "") {
            email_error.html("Please enter your email ");
            deferred.reject();
        }
        // if it's valid email
        else if (filter.test(a) == false) {
            email_error.html("Please enter Valid email address");
            deferred.reject();
        } else if (filter.test(a) == true) {
            console.log("elseif");
            var baseUrl = '<?= base_url() ?>';

            $.ajax({
                        type : "POST",
                        url : baseUrl + "index.php/index/validateUserEmail",
                        data : "useremail=" + $("#email").val(),
                        success : function(msg) {
                            alert(msg);
                            if (msg == "1") {
                                $("#tick_cross").fadeIn("slow")
                                        .html('<img src="' + baseUrl
                                                + 'images/cross.png" />');
                                $("#emailValidate").val("1");
                                email_error
                                        .html("This email-Id already exists!");
                                deferred.reject();
                            } else {

                                $("#tick_cross").fadeIn("slow")
                                        .html('<img src="' + baseUrl
                                                + 'images/tick.png" />');
                                $("#emailValidate").val("0");
                                email_error.html(" ");
                                console.log("alok");
                                deferred.resolve();
                            }

                        }
                    });

        }

        else {
            email_error.html(" ");
            deferred.resolve();
        }

        return deferred.promise();
    }
});

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0

The problem is the AJAX call takes time, but you're if statement requires an immediate return. I'm also not sure if returning false is enough, I believe you need to capture the event and call the preventDefault() method on it...

The best thing to do would be to change your <input type="submit" /> button to <input type="button" id="submitButton" /> and then remove the form.submit() handler you have now entirely. Add this:

$(function(){
    $('#submitButton').click(validateEmail)

})

and then add $("#signupForm").submit() to your validateEmail() function:

function validateEmail(){
    //if it's NOT valid
    alert("In email");
    var a = $("#email").val();
    var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+@[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;

    if(email.val() == ""){
        email_error.html("Please enter your email ");
        return false;
    }
    //if it's valid email
    else if(filter.test(a)==false){
        email_error.html("Please enter Valid email address");
        return false;
    }
    else if(filter.test(a)==true){alert("elseif");
    var baseUrl = '<?= base_url() ?>';

            $.ajax({
                type: "POST",
                url: baseUrl+"index.php/index/validateUserEmail",
                data: "useremail="+$("#email").val(),
                success: function(msg){
                alert(msg);
                if(msg == "1")
                    {
                        $("#tick_cross").fadeIn("slow").html('<img src="'+baseUrl+'images/cross.png" />');
                        $("#emailValidate").val("1");  
                        email_error.html("This email-Id already exists!");
                        return false;
                    }
                    else
                    {

                        $("#tick_cross").fadeIn("slow").html('<img src="'+baseUrl+'images/tick.png" />');
                        $("#emailValidate").val("0");
                        email_error.html(" ");
                        alert("alok");
                        $("#signupForm").submit() // <--- HERE
                        return true;
                    }


                }
            });

    }

    else{
    email_error.html(" ");
    return true;
    }

}

You could probably clean it up a bit more now too...

Thom Porter
  • 2,604
  • 2
  • 19
  • 23
0

You need to set the option async : false

Captain Payalytic
  • 1,061
  • 8
  • 9
  • yeah, read the docs: Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active. As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done() or the deprecated jqXHR.success(). – Thom Porter Mar 20 '13 at 12:02
0

I think you have to wait untill response has finished. readyState==4

$.ajax({
                    type: "POST",
                    url: baseUrl+"index.php/index/validateUserEmail",
                    data: "useremail="+$("#email").val(),
                    success: function(){

                }).done(function (msg) {

alert(msg);
                    if(msg == "1")
                        {
                            $("#tick_cross").fadeIn("slow").html('<img src="'+baseUrl+'images/cross.png" />');
                            $("#emailValidate").val("1");  
                            email_error.html("This email-Id already exists!");
                            return false;
                        }
                        else
                        {

                            $("#tick_cross").fadeIn("slow").html('<img src="'+baseUrl+'images/tick.png" />');
                            $("#emailValidate").val("0");
                            email_error.html(" ");
                            alert("alok");
                            return true;
                        }


                    }
})
.fail(function() { alert("error";
 return true;
); });
Mitch Bukaner
  • 171
  • 13