Adam Adam - 2 months ago 6
jQuery Question

jQuery-validate: Using remote hides button?

When I use the remote method from the jQuery Validation Plugin and press the submit button, then the submit button name is not listed in the

$_POST
array. Is this a bug or am I doing something wrong?

Here is a small example:

<?php
if(!empty($_POST))print_r($_POST);
?>
<form method="POST" id='mainForm'>
<input type='email' name="email" value="test@test.com">
<button name="superbutton">Press me</button>
</form>


When I press the
superbutton
I get the following output
enter image description here

When I add the jQuery Validation Plugin like this

$("#mainForm").validate({
rules: {
email: {
required: true,
email: true
}
}
});


I still get the same output. However, when I add the remote method:

$("#mainForm").validate({
rules: {
email: {
required: true,
email: true,
remote: {
url: "test.php"
}
}
}
});


with test.php

<?php
header('Content-Type: application/json');
echo json_encode("true");


Then
superbutton
is no longer in the '$_POST` array.

enter image description here

Am I doing anything wrong here?

Answer

When using local validation methods, jquery-validate calls event.preventDefault() when validation fails, and otherwise returns normally to allow the normal form submission to occur.

This isn't possible with remote validation, because AJAX is asynchronous. It doesn't wait for the response, so it always prevents normal form submission. When the AJAX response is received, it uses Javascript form.submit() to submit the form.

When a form is submitted with Javascript, the button that triggered the original submission is not known by the browser, so it won't be included in the POST data.

Comments