简体   繁体   中英

jQuery validation , submit handler, and submit form

I am having some problems on executing the following code.

  1. The code submits but it doesnt do anything, it comes back to the same screen, it seems that the values of the form have been not submited.

     <script type="text/javascript"> $(document).ready(function(){ $("#signin_form").validate({ debug: false, rules: { /// }, messages: { /// }, submitHandler: function(form) { var result; $.post('test.php', $('#signin_form').serialize(), function(data){ result = $.parseJSON(data); if (result.flag == 'false'){ $('#results').show() } }) .success(function(data){ if (result.flag == 'true'){ form.submit(); } }, 'json'); } }); }); </script> 
  2. If I change the code to the following, it works and it takes me to the proper screen, but i need to validate, a captcha code, i am not sure if it is the right place to do it, i tried to use beforeSubmit but then the captcha is not validated.

     <script type="text/javascript"> $(document).ready(function(){ $("#signin_form").validate({ debug: false, rules: { /// }, messages: { /// }, submitHandler: function(form) { form.submit(); } }); }); </script> 

There is something about the $.post that i dont underestand... and doesnt submit the information.

Does anyone know what it could be? thanks!

You don't need to change how the form submits, in this case, for validating the captcha, use remote function from jquery.validate .

There are some problems around the remote usage with jquery.validate . Check if you did the following:

1) Make sure you are using jQuery version 1.6.1 and above only.

2) Use the "synchronous" option for remote execution (default being asynchronous) and to do this set async argument to false.


Example of usage:

Suppose this is my form...

HTML:

Add id and name attributes to all the form elements or just the captcha (this one must have both).

<form id="signin_form" action="save.php" method="POST">
  Enter captcha: O1S2C3A4R
  <br/>
  <input type="text" id="captcha" name="captcha" value=""/>
  <input type="submit" id="save" name="save" value="Save"/>
</form>

jQuery:

Add type , async and data arguments. This last argument passes the captcha value to check.php file and that's why that element needs the id attribute. Then you are able to use this selector $('#captcha') .

(For me this is better but you can also call the element by name using other selector type)

Just to know, you need to also define an error message for the remote , in this case I used Invalid captcha .

$(document).ready(function(){

    $("#signin_form").validate({
        rules: {
            captcha: {
                required: true,
                remote: { 
                    url:"check.php",
                    type:"post",
                    async:false,
                    data: {
                        /* this is the name of the post parameter that PHP will use: $_POST['captcha'] */
                        captcha: function() {
                            return $.trim($("#captcha").val());
                        }
                    }
                }
            }
        },
        messages: {
            captcha: {
                required: "*",
                remote: "Invalid captcha"
            }
        }
    });

});

PHP: check.php

At this point it is important to use "true" or "false" as string to let know the jquery.validation plugin if the captcha is valid or not. In this case, if captcha is equals to O1S2C3A4R then is valid and, at client side, you will look that the submit will process the form to save.php file specified in the html form action attribute.

<?php

    $captcha = $_POST['captcha'];

    if($captcha == "O1S2C3A4R"){
        echo "true";
    } else {
        echo "false";
    }

?>

Doing this way, you can validate the whole form without problems and also check the captcha value remotely without altering plugin functionality.

Also you can test all this code together and look that it works :-)

Hope this helps.

Javascript:

<script type="text/javascript">
    $(document).ready(function(){
        $("#signin_form").validate({
            rules: {
                captcha: {
                    remote: {
                        url: "remote.php"
                        }
                    }
                }
            },
            messages: {
                captcha: {
                    remote: "Please enter the text in the captcha."
                }
            }
        });
    });
</script>

HTML form:

<form id="signin_form">
    <input type="text" name="captcha">
    <input type="submit">
</form>

PHP:

$response = $_GET['captcha']; 
$answer  = 'captcha_answer';

if($response==$answer){
    echo 'true'; 
} else {
    echo 'false'; 
}

Sorry for shoving this part into an answer -- I'm not allowed to comment:

Keep in mind that setting the 'async' parameter to false will lock up your page until you get a response, which might not be what you want. The validation library should block normal form submission if it's waiting on a response for remote validation, at least in newer versions (I'm using jQuery 1.7.2 and Validation 1.10.0).

IIRC the jQuery Validate library will treat anything other than the exact string "true" as being an error. This can be used to pass different custom messages depending on the reason for rejection. json_encode adds extra quotation marks that cause jQuery Validate to see it as a custom error message.

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