Seeing as I can't find a solution for my problem I might going about this wrong.
I'm trying to build a form using AJAX that will provide an error response or a successful response upon submitting a form. I am able to get an error response sent to my form, but it is in JSON, which obviously looks bad. For the moment I am using a simplified form with just two requirements: (1) name must be John and (2) the date must be in the future.
Here is my html:
<!DOCTYPE html>
<head>
<title>AJAX Form</title>
</head>
<body>
<form action="ajax/contact.php" method="post" class="ajax">
<div>
<input type="text" name="name" placeholder="Your name">
</div>
<div>
<input type="text" name="email" placeholder="Your email">
</div>
<div>
<input type="text" placeholder="" class="textinput" name="departuredate" id="departing">
</div>
<div>
<textarea name="message" placeholder="Your message"></textarea>
</div>
<input type="submit" value="Send">
</form>
<div id="ack"></div>
<script type="text/javascript" src="js/jquery-1.11.0.js"></script>
<script type="text/javascript" src="js/main.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.10.4.custom.js"></script>
<script>
$(document).ready(function() {
$("#departing").datepicker({
//minDate: 0,
//maxDate: "+1y",
dateFormat: "yy-mm-dd",
defaultDate: new Date(),
});
});
</script>
</body>
</html>
Here is my PHP file:
<?php
$errors = array();
$form_data = array();
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
$date = htmlspecialchars($_POST['departuredate']);
$message = htmlspecialchars($_POST['message']);
if (date('Y-m-d') > $date) {
$errors['date'] = "Date is in the past";
goto end;
}
if ($name != 'John') {
$errors['name'] = "Name is not John";
goto end;
}
end:
if (empty($errors)) {
$form_data['success'] = true;
} else {
$form_data['errors'] = $errors;
}
echo json_encode($form_data);
?>
Here is my AJAX file:
$('form.ajax').on('submit', function() {
var that = $(this),
url = that.attr('action'),
type = that.attr('method');
$.ajax({
url: url,
type: type,
data: that.serialize(),
dataType: 'json',
cache: false,
success:
function(result) {
if(!result.success) {
$('#ack').html(JSON.stringify(result.errors));
console.log(result.errors);
} else {
console.log('Valid date and name entries');
}
}
});
return false;
});
Thanks!