简体   繁体   中英

Validate a form with javascript before submitting with ajax?

I've been making a website and I want a nice login/registration/forgot pass form.

I wanted to use 'ajax' to make it nice for the user and, consequently, have spent the last 2 weeks on a steep learning curve.

I wanted to check my form is valid so I used some javascript and executed it via the onsubmit function. However, my ajax just submits regardless so now I'm wondering if I would be better validating via the jquery script?

Here is my code so far:

jQuery(document).ready(function($) {

$('#JTlogin_titleText').text("Register or log in");
$("input[type='submit'][name='submit']").val("Send");
$('#JTlogin_wrapper #forgotpass_div').hide();
$('#JTlogin_wrapper #matchPass_div').hide();


$('form#loginFormID #username').change(function(){
$('form#loginFormID span.JTlogin_usernameStaticMessage').hide();
$('form#loginFormID span.JTlogin_usernameErrorMessage').hide();
$('form#loginFormID span.JTlogin_usernameDynamicMessage').show();

$('form#loginFormID span.JTlogin_usernameDynamicMessage').html("<div class='login_message_box'><img src='"+ajax_login_object.ThemeFolder+"/images/loginbox/loading20x20.gif' class='JTloginFormImage'> checking...</div>");


          $.ajax({
                type:"post",
                dataType: 'json',
                url:ajax_login_object.ThemeFolder+ajax_login_object.auxFunctionsFolder+"/check_login_details.php",
                data: { 
                    'username': $('form#loginFormID #username').val() },                   
                    success:function(data){
                    if(data.existing_user == true){
                        $('form#loginFormID span.JTlogin_usernameDynamicMessage').html("<div class='login_message_box'><img src='"+ajax_login_object.ThemeFolder+"/images/loginbox/tick.png' class='JTloginFormImage'> Welcome back - please log in "+data.userFirstName+"</div>");
                        $('#loginSubmit').removeAttr("disabled");
                        $('#JTlogin_wrapper #matchPass_div').hide();
                    }
                    else{
                        if( data.errorMsg ) {
                            $('form#loginFormID span.JTlogin_usernameDynamicMessage').hide();
                            $('form#loginFormID span.JTlogin_usernameErrorMessage').show();
                            $('form#loginFormID span.JTlogin_usernameErrorMessage').html("<div class='login_message_box'><img src='"+ajax_login_object.ThemeFolder+"/images/loginbox/cross.png' class='JTloginFormImage'> "+data.errorMsg+"</div>");  
                            $('#JTlogin_wrapper #matchPass_div').hide();                            
                            $('#loginSubmit').attr('disabled', 'disabled');
                        } else {
                        $('form#loginFormID span.JTlogin_usernameDynamicMessage').html("<div class='login_message_box'><img src='"+ajax_login_object.ThemeFolder+"/images/loginbox/tick.png' class='JTloginFormImage'> Welcome - click submit to register</div>");
                        $("input[type='submit'][name='submit']").val("Register");
                        $('#JTlogin_wrapper #matchPass_div').fadeIn('slow');
                        $('#loginSubmit').removeAttr("disabled");
                      }
                    }
                }
             });
        });




// Perform AJAX forgot pass on form submit
$('form#forgotPassFormID').on('submit', function(e){
    $('form#loginFormID #JTlogin_titleText').text(ajax_login_object.loadingmessage);
    $.ajax({
                type:"post",
                dataType: 'json',
                url:ajax_login_object.ThemeFolder+ajax_login_object.auxFunctionsFolder+"/check_login_details.php",
                data: { 
                    'username': $('form#loginFormID #username').val(),
                    'resetpass': true },                   
                    success:function(data){
                        //alert('here');
                    }
    });
    e.preventDefault();
});


$('#loginFormID #change_to_forgot_pass').click(function(){
$('#JTlogin_titleText').text("Forgotten your password");
$('#JTlogin_wrapper #login_div').hide();
$('#JTlogin_wrapper #forgotpass_div').fadeIn('slow');
});

$('#forgotPassFormID #change_to_login').click(function(){
$('#JTlogin_titleText').text("Register or log in");
$('#JTlogin_wrapper #forgotpass_div').hide();
$('#JTlogin_wrapper #login_div').fadeIn('slow');
});




// Perform AJAX login on form submit
$('form#loginFormID').on('submit', function(e){
    $('#JTlogin_titleText').text(ajax_login_object.loadingmessage);

        $.ajax({
        type: 'POST',
        dataType: 'json',
        url: ajax_login_object.ajaxurl,
        data: { 
            'action': 'ajaxlogin', //calls wp_ajax_nopriv_ajaxlogin
            'username': $('form#loginFormID #username').val(), 
            'password': $('form#loginFormID #password').val(), 
            'password2': $('form#loginFormID #password2').val(),                
            'security': $('form#loginFormID #security').val() },
        success: function(data){
            $('#JTlogin_titleText').text(data.message);
            if (data.loggedin == true){
                document.location.href = ajax_login_object.redirecturl;
            }
        },
        error: function(data){ 
                alert("Apologies, there has been an error. Please try again."); 
        }
    });

    e.preventDefault();
});


});

My form has this onsubmit....

<form id="loginFormID" onsubmit="return validateLoginFormOnSubmit(this)" action="login" method="post" autocomplete="on">

I then have some javascript that checks the form is populated correctly and returns true if it is and returns false if it isn't.

I only want to execute my ajax query if it returns true.

So... my questions are: 1) Do you know how I would do this? 2) Is there a better way of doing this?

I also feel like my jquery stuff is growing arms and legs and feel that I could probably do what I'm attempting with a lot fewer lines of code if I had a scooby-doo about what I'm doing! So.. any help would be very gratefully received.

Cheers

John ;-)

<form id="loginFormID" onsubmit="return validateLoginFormOnSubmit();" method="post" autocomplete="on">

JavaScript

funciton validateLoginFormOnSubmit() {

        //do client side validation 

        if(true == validation) {
             //do the `ajax` call with serialized form data
        }
        else {
            //show error 
        }

        return false; // because we want to submit only through `ajax`, so stopping original form submit.
}

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