I handle it if the PHP returns successfully, but as far as errors go I'm a little confused as to what I should be doing.
What I was thinking of doing since the following code for error:
doesn't work, was in my PHP setting the mail function equal to a variable in order to save the result of the function. Then in my jQuery, testing the result of the variable to find whether or not it's true.
However this would all occur under success:
when it seems like clearly error should be handling this.
How do I have it so success:
handles the successes correctly and displays a message while error:
will handle the errors by returning the errors then I'll be able to display them to the user.
Also bonus points if you can tell me if my .html()
function is done well? It looks messy formatting-wise, but I can't seem to figure a nicer way to do it.
jQuery:
// Following section submits form without refreshing page
var dataString = "name=" + nameVal + "&email=" + emailVal + "&message=" + messageVal;
$.ajax({
type: "POST",
url: "mail.php",
data: dataString,
success: function() {
$(".contact-form").hide();
$(".alt-contact").hide();
// Inserts divs making up the success message for the form submission
$(".contact-form").html("<div class='success-message'><div class='success-image'></div><div class='success-title'>Success! The message has been sent!</div><div class='success-body'>I'll get back to you right away.</div></div>");
$(".contact-form").fadeIn(500);
}
error: function() {
$(".contact-form").hide();
$(".alt-contact").hide();
// Inserts divs making up the success message for the form submission
$(".contact-form").html("<div class='error-message'><div class='error-image'></div><div class='error-title'>Success! The message has been sent!</div><div class='error-body'>I'll get back to you right away.</div></div>");
$(".contact-form").fadeIn(500);
}
});
return false;
PHP:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$recipient = 'me@christianselig.com';
$subject = 'Message From Website';
$body = '<b>From:</b> ' . $name . '
' . $message;
$headers = 'From: ' . $email . '
';
$headers .= 'Content-type: text/html; charset=UTF-8' . '
';
mail($recipient, $subject, $body, $headers);
?>