I am trying to create ajax and php files so when a user enters data on the form it either displays an error message if its invalid or sends and email and displays a thank you message if it is valid. I am stuck and not sure why my code is not working, right now when I hit submit the page is just reloaded with no messages at all.
AJAX code:
$('document').ready(function () {
var request;
$('contact').submit(function(event) {
event.preventDefault();
if (request) {
request.abort();
}
var $form = $(this);
var $inputs = $form.find("inputs, select, buttons, textarea");
var serializedData = $form.serialize();
$inputs.prop("disabled", true);
request = $.ajax({
url: "../send_email.php",
type: "post",
data: serializedData
});
request.done(function (msg) {
alert(msg);
});
request.fail(function (jqXHR, textStatus, errorThrown) {
console.error(
"The following error occurred: "+
textStatus, errorThrown
);
});
request.always(function () {
$inputs.prop("disabled", false);
});
});//contact event
});//document ready
PHP code:
<?php
if(isset($_POST['email'])) {
$email_to = "[email protected]";
$email_subject = "Personal Website Contact Form";
$error_message = "";
if(!isset($_POST['first_name']) ||
!isset($_POST['last_name']) ||
!isset($_POST['email']) ||
!isset($_POST['comments']))
{
$error_message .= 'Please fill in all fields.\n'
}
else{
$first_name = $_POST['first_name']; // required
$last_name = $_POST['last_name']; // required
$email_from = $_POST['email']; // required
$comments = $_POST['comments']; // required
$email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if(!preg_match($email_exp,$email_from)) {
$error_message .= 'The Email Address you entered does not appear to be valid.\n';
}
$string_exp = "/^[A-Za-z .'-]+$/";
if(!preg_match($string_exp,$first_name)) {
$error_message .= 'The First Name you entered does not appear to be valid.\n';
}
if(!preg_match($string_exp,$last_name)) {
$error_message .= 'The Last Name you entered does not appear to be valid.\n';
}
if(strlen($comments) < 2) {
$error_message .= 'The Comments you entered do not appear to be valid.\n';
}
if(strlen($error_message) == 0) {
$email_message = "Form details below.\n\n";
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
$email_message .= "First Name: ".clean_string($first_name)."\n";
$email_message .= "Last Name: ".clean_string($last_name)."\n";
$email_message .= "Email: ".clean_string($email_from)."\n";
$email_message .= "Comments: ".clean_string($comments)."\n";
// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
@mail($email_to, $email_subject, $email_message, $headers);
echo "Email Sent. Thank you, I will get back to you asap";
}
else{
echo $error_message;
}
}
}
?>
$('contact')should probably be either$('#contact')(if the form hasid="contact") or$('.contact')(if the form hasclass="contact").