I’m keen to use the jQuery validator plugin to validate my code, but I would like to disable to automatic submitting of my form. I’d rather send it myself using the jQuery $.post method.
In fact, I’m not really sure why my form is submitting considering that my buttons aren’t of type submit but are just <button></button>.
<form id="my_form" name="my_form" method="post" action="">
...
<button id="previous_button" class="nav-button">Previous</button>
<button id="next_button" class="nav-button">Next</button>
</form>
and my onClick listener, in which I am hoping that on valid input I can post the form data and then move to a new page, else reposition the window so that the user sees the `error_messages’ box where all my error messages show up.
$('#next_button').click(function(event) {
validateAndSave();
});
function validateAndSave() {
if($('#my_form').valid()) {
$.post('save_form_to_database.php',
$('#my_form').serialize());
window.location = 'next_page.php';
} else {
// reposition to see the error messages
window.location = '#error_messages';
}
}
The result of this though (and the result is the same whether debug is set to true or false) is that on valid input, I can see by looking at the status bar that `next_page.php’ flashes up briefly and then I get taken back to my original page again. Also on failure of validation, my page doesn’t seem to reposition itself properly.
So my questions are:
-
Why is my page being redirected back to the original page?
-
How can I use the validator to validate, but then post the form my own way using $.post?
Many thanks in advance.
Update thanks to the responses
According to this page on the button element:
The TYPE attribute of BUTTON specifies the kind of button and takes the value submit (the default), reset, or button
So my buttons were taking the default value of type="submit"
Specify your buttons as type=”button” to stop the automatic submit. This one gets me all the time.