You can try passing arrays from your PHP script back to your AJAX response as data, and let your script handle whatever that is passed back :) In my example below, I have chosen to pass the PHP response back to your AJAX script using the json_encode
function, and arbitrarily selected a type of status code that will be read by your JS function to take appropriate action :)
Also, in order your $.ajax
to read JSON data correctly, you should include the line dataType: "json"
in the function.
Overall, the suggested changes will be:
- Echo a response from your PHP script in JSON format using
json_encode()
- Allows your PHP script to pass the response to your JS script
- Ensure that your AJAX function reads the JSON format, and then take the appropriate action
For example, in your PHP script, you can use:
if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
// If email is valid
$email = $_POST['email'];
$message = $_POST['message'];
$formcontent="From: $name \n Message: $message";
$recipient = "example@example.com";
$subject = "Contact Form";
$mailheader = "From: $email \r\n";
if(mail($recipient, $subject, $formcontent, $mailheader)) {
// If mail is sent
// Status is arbitrary. You can use a string, number... I usually use numbers
$resp = array("status"=>1, "message"=>"Mail successfully sent.");
} else {
// If sending failed
$resp = array("status"=>2, "message"=>"Error with sending mail.");
}
} else {
// If email failed filter check
$resp = array("status"=>3, "message"=>"You have provided an invalid email address. Please check the email address provided.");
}
// Echos the $resp array in JSON format, which will be parsed by your JS function
echo json_encode($resp);
In your JS file, you can parse the JSON response:
$('.form').submit(function() {
// Define variables to construct dataString. You don't need to use var to declare each variable individually ;)
var name = $(".name").val(),
email = $(".email").val(),
message = $(".message").val();
// Construct dataString
var dataString = 'name=' + name + '&email=' + email + '&message=' + message;
// Ajax magic
$.ajax({
type: "POST",
url: "mail.php",
data: dataString,
dataType: "json",
cache: false,
success: function(data) {
if(data.status == "1") {
$(".form").hide();
$(".notice").fadeIn(400);
} else if (data.status == "2") {
// Error handling for failure in mail sending
} else if (data.status == "3") {
// Error handling for failure in email matching
} else{
// Catch all other errors
}
}
});
return false;
});