I'm attempting to send an AJAX call to my php file to send an email after a contact form is filled out. I had this working perfectly when I was just trying to get the echo response from php and put it in my div above my form, but I wanted to append some data and add a class after it came back successful to give it a better look. Right now, with this code, the email still sends through, but the message or class does not show up.
What am I doing wrong? How can I get the response from php to display in the contactSuccess div while appending everything and hiding the contactSuccess div until it has successfully come through?
<script>
$(document).ready(function(){
$('#submit').click(function(){
$.post("contactSend.php", $("#mycontactform").serialize(), function(response) {
//test
$('#contactMessageStatus').append(data);
$('#contactMessageStatus').addClass("contactSuccess");
$('html, body').animate({
scrollTop: $("#contactMessageStatus").offset().top
}, 2000);
//endtest
$('#contactMessageStatus').html(response);
//$('#success').hide('slow');
});
return false;
});
});
</script>
Form
<div id="contactMessageStatus"></div>
<form action="" method="post" id="mycontactform" >
<input type="text" class="inputbar" name="name" placeholder="Full Name" required>
<input type="email" class="inputbar" name="email" placeholder="Email" required>
<input type="message" class="inputbar" name="message" placeholder="Message" required>
<input type="button" value="Send Message" id="submit">
</form>
CSS
#contactSuccess {
border-style: solid !important;
border-width: 1px !important;
background-position: 10px 9px !important;
background-repeat: no-repeat !important;
min-height: 24px !important;
padding: 8px 8px 8px 32px !important;
font-size: 11px !important;
font-weight: bold !important;
border-color: #446423;
background-color: #eff5ea;
background-image: url(success_check.gif);
color: #3d6611;
}
PHP file - Adding this just in case
<?php
// Here we get all the information from the fields sent over by the form.
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$to = 'contact@example.com';
$subject = 'SFL Contact Form Submitted';
$message = 'FROM: '.$name. ' ' . ' Email: '.$email. ' ' . 'Message: '.$message;
$headers = 'From: contact@example.com' . "
";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) { // this line checks that we have a valid email address
mail($to, $subject, $message, $headers); //This method sends the mail.
echo "Your email was sent!"; // success message
}else{
echo "Invalid Email, please provide an correct email.";
}
?>