jQuery validate submitHandler does not work in firefox

8

With the following function below, I can send the data via ajax quietly in Chrome, but when testing in Firefox, no error occurs and data is not sent.

$('#form_lista_amiga').validate({
    rules : {
        cpf: { required: true, cpf: true }
    },
    submitHandler: function(form) {

        var data = $( form ).serialize();
        event.preventDefault();
        $.ajax({
            url: "<?php echo Router::url(array('controller' => 'ListaAmiga', 'action' =>'add'), true); ?>",
            type: 'POST',
            datatype: 'json',
            data: data,
            success: function(data){
                $('#lista_amiga_msg').html(data);
                // alert(data);
            }
        });  
        return false;   
    }
});
    
asked by anonymous 26.02.2015 / 18:36

2 answers

2

I gave a hoot here with your code and I came to the conclusion that event.preventDefault() causes a discrepancy in the way FireFox works with Chrome.

If the code contains event.preventDefault() then it works in Chrome, but in FireFox it does not work ... instead it seems to submit the form normally.

When commenting on the event.preventDefault() line, then FireFox behaved the same way as Chrome.

This was the code I tested and worked on both browsers:

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src="/libs/jquery-1.11.2.min.js"></script>
    <script type="text/javascript" src="/libs/jquery.validate-1.13.1.js"></script>
    <link href="/libs/bootstrap-3.2.0.min.css" type="text/css" rel="stylesheet" />

    <script type="text/javascript">
        $(function() {

            jQuery.validator.addMethod("cpf", function(value, element) {
                return (/\d{3}.\d{3}.\d{3}-\d{2}/g).test(value);
            }, "* CPF inválido");

            $('#form_lista_amiga').validate({
                rules : {
                    cpf: { required: true, cpf: true }
                },
                submitHandler: function(form) {

                    var data = $( form ).serialize();
                    //event.preventDefault();
                    $.ajax({
                        url: "add",
                        type: 'POST',
                        datatype: 'json',
                        data: data,
                        success: function(data){
                            alert(data);
                        }
                    });  
                    return false;

                }
            });

        });
    </script>
</head>
<body>
    <form id="form_lista_amiga">
        <input id="cpf" name="cpf" />
        <input type="submit" value="send" />
    </form>
</body>
</html>
    
25.03.2015 / 12:44
0

If you want to use the event, use this pattern:

$("#form").submit(function(e) {
    e.preventDefault();
}).validate({
    rules: {...},
    submitHandler: function(form) { 
        //codigo
        return false;
    }
});
    
16.08.2016 / 01:25