I have the following HTML and jQuery Ajax code:
<form>
<input name="name_field" type="text">
<button type="submit">Save</button>
</form>
$(document).on("submit", "form", function(event) {
event.preventDefault();
$(".error").hide("blind", function() {
$.ajax({
url: 'php/script.php',
type: 'POST',
dataType: 'json',
data: $(this).serialize(),
success: function(data) {
console.log(data);
}
});
});
});
This is my PHP code:
<?php
$name = $_POST['name_field'];
?>
When I submit the form, it shows the following error:
Undefined index: name_field
However, when I change my jQuery Ajax to not wait for the .error
class to finish, it shows no error and works perfectly fine:
$(document).on("submit", "form", function(event) {
event.preventDefault();
$(".error").hide("blind"); // remove function() here
$.ajax({
url: 'php/script.php',
type: 'POST',
dataType: 'json',
data: $(this).serialize(),
success: function(data) {
console.log(data);
}
});
});
Why does it do this and how can I fix it?