Xroad Xroad - 3 months ago 11
jQuery Question

Stay on the page with jQuery Validate plugin

When I click on the submit button of my form I'm redirected because of the PHP on the page "Form sent". How to stay in the same page with jQuery validate form plugin please ?

PHP FILE

<?php
// [I HAVE CUT THE CODE]

if(mail($to, $subject, $message, $headers)){
echo "Form sent";
} else {
echo "Form not sent";
}
?>


JQUERY FILE

$("#form-contact").validate({

submitHandler: function(form) {
$('.btn-validate-group:visible').hide();
$('.message-success').fadeIn(1000);
form.submit();
}

});


HTML FILE

<form id="form-contact" action="php/traitement.php" method="post"></form>


UPDATE 1

submitHandler: function(form) {
$('.btn-validate-group:visible').hide();
$('.message-success').fadeIn(1000);
$.ajax({
type: "POST",
url: url,
data: data,
success: function(result){ console.log("success!", result);},
dataType: dataType
});
return false;
}


I'm always redirected on "Form sent" page. I know nothing about Ajax :-/

UPDATE 2

http://jsfiddle.net/Xroad/2pLS2/25/

Answer

jQuery .ajax() can be used to submit data to the server without a page refresh, but it's not exclusive to the jQuery Validate plugin.


However, here are your two options using the jQuery Validate plugin.

Standard form submit using the default action of the form element (as you've done)...

$("#form-contact").validate({
    submitHandler: function(form) {
        $('.btn-validate-group:visible').hide();
        $('.message-success').fadeIn(1000);
        form.submit();  // standard submit of the default form action
    }
});

To stay on same page, use .ajax() in the submitHandler callback...

$("#form-contact").validate({
    submitHandler: function(form) {
        $('.btn-validate-group:visible').hide();
        $('.message-success').fadeIn(1000);
        $.ajax({    // submit form using ajax
            // your ajax options here
        });
        return false;  // block default form action  
    }
});

See the jQuery .ajax() documentation for the options.


This is your own jsFiddle, which shows everything is working. I cannot test the ajax but the form is not refreshing the page as you claim.

Comments