Reputation: 1317
I am trying to get this ajax form just to return a success message but only ever get the error 'film id is required'. (Eventually I will insert the form values into a mysql database). Please can anyone tell me what I am doing wrong? Many thanks.
The form
<form action="process.php" method="POST">
<div id="film_id-group" class="form-group">
<label for="film_id">Film_id</label>
<input type="text" class="form-control" name="film_id" placeholder="film_id">
</div>
<button type="submit" class="btn btn-success">Submit <span class="fa fa-arrow-right"></span></button>
</form>
Process.php
<?php
$errors = array();
$data = array();
$film_id = $_POST['film_id'];
if (empty($_POST['film_id']))
$errors['film_id'] = 'Film Id is required.';
if ( ! empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
} else {
$data['success'] = true;
$data['message'] ='sucess!';
}
echo json_encode($data);
?>
The javascript.
$(document).ready(function() {
// process the form
$('form').submit(function(event) {
$('.form-group').removeClass('has-error'); // remove the error class
$('.help-block').remove(); // remove the error text
var formData = {
'film_id' : $('input[film_id=film_id]').val(),
};
// process the form
$.ajax({
type : 'POST',
url : 'process.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json',
encode : true
})
// using the done promise callback
.done(function(data) {
console.log(data);
if ( ! data.success) {
// handle errors
if (data.errors.film_id) {
$('#film_id-group').addClass('has-error');
$('#film_id-group').append('<div class="help- block">' + data.errors.film_id + '</div>');
}
} else {
$('form').append('<div class="alert alert-success">' + data.message + '</div>');
}
})
.fail(function(data) {
});
event.preventDefault();
});
});
Upvotes: 0
Views: 59
Reputation: 17351
The line:
'film_id': $('input[film_id=film_id]').val(),
in your AJAX formData
object should be:
'film_id': $('input[name=film_id]').val()
(Also make sure to remove the trailing comma, because there is no element after it.)
Your code is searching for an <input>
element like the following:
<input film_id="film_id" />
This is incorrect. Your selector should have name
as the attribute name, not film_id
.
Therefore, because there is no such element, this would send nothing to the PHP file (""), which would evaluate as false, as per the documentation.
Upvotes: 2