简体   繁体   中英

How to prevent form to submit in user availability check process?

I have a registration form where i am checking user availability using jquery, but when user is not available form should not be submitted. How to prevent it to submitted in not availability case. My code is

$(document).ready(function(){
    $('#email').change(function() {
        status=0;
        user=$('#email').val();
        $.ajax({
            type:"post",
            url:"verify-user.php",
            data:{'user':user},
            success:function(data){
                if(data=='1'){
                    $("#show_msg").html('<span style="color:#F00;">Not avilable</span>');
                }else if(data=='0'){  
                    $("#show_msg").html('<span style="color:#093;">Avilable</span>');
                }
            }
        });  
    });
});

Please help me. Your help would be appreciated. Thanks in advance.

The code to prevent form submission is tied to the event - in this case:

$('#email').change

You need to pass the event to your event handler function as an argument, and add

event.preventDefault()

to your email change handler. However, since you are calling your validation via Ajax, I believe you'll have to manually submit the form if your validation succeeds. Edited code below - not tested, but hopefully will lead you in the right direction.

$(document).ready(function() {

    $('#email').change(function(event) {

        status=0;

        user=$('#email').val();

        // prevent default action
        event.preventDefault();

        $.ajax({

            type:"post",

            url:"verify-user.php",

            data:{'user':user},

            success:function(data){

                if(data=='1'){

                    $("#show_msg").html('<span style="color:#F00;">Not avilable</span>');

                } else if (data=='0') {  

                    $("#show_msg").html('<span style="color:#093;">Avilable</span>');

                   //submit your form if validation succeeds
                    $("#your-form-id").submit();

            }

        }

    });  

});

});

Couldn't you just use an if statement?

var user=$('#email').val();
if (!user) {
   return;
}

$.ajax({

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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