Reputation: 73
I have a problem with my jquery script, it is returning error when I try to send the date value from my form, when I leave it in blank, it doesn't show me an error.
<div class="field-wrap">
<input type="date" name="fecha_nacimiento" required autocomplete="off" maxlength="30" placeholder="Fecha de nacimiento">Fecha de nacimiento</input>
</div>
<script>
$(function(){
$('#entrarBt').click(function(){
$.ajax({
url: 'registro_dpb.php',
type: 'POST', // GET or POST
data: $("#miForm").serialize(), // will be in $_POST on PHP side
success: function(data) { // data is the response from your php script
// This function is called if your AJAX query was successful
alert("Response is: " + data);
},
error: function() {
// This callback is called if your AJAX query has failed
alert("Error!");
}
});
});
});
</script>
Upvotes: 0
Views: 960
Reputation: 33933
Your problem was pretty subtile... Making it hard to find.
But the solution is really simple.
You use a <button>
inside a <form>
which is absolutely correct.
But you have to know that in HTML5, if the type of a <button>
is not explicitly defined as "button", its default type is "submit".
Reference here.
This was the issue...
Since you want to submit using an ajax request, which allow to receive a response without reloading the page, you have to "prevent" this normal behavior of a <button>
.
The submit made by the button was not sent to your PHP script, but to your HTML page (there was no other action
defined in the <form>
tag, so the default is "self".
So the page reloads... Making your ajax request to fail.
So there is two ways to fix this:
1: Define the button type
as "button":
<button type="button" id="entrarBt" [+ other attributes]>Entrar</button>
or
2: Prevent this default behavior using prevent.default()
in you click handler.
$('#entrarBt').click(function(e){
e.preventDefault();
$.ajax({
//...
I think the second one is more evident for another programmer who could review your code, but the first is ok too.
Fixing this completely resolved the issue.
This is a tricky thing to absolutely know!
In short, a <button>
within a HTML5 <form>
is a submit by default!
Upvotes: 1