Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
322 views
in Technique[技术] by (71.8m points)

jquery - 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 ;-)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
<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.
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...