I know this has been answered before, but I still can't seem to find a solution that works for me. I have a form submission that is not working with the ajax call. I'm pretty sure its not the HTML or PHP, because If i execute the php directly, everything works fine. when going through ajax however, I get the console log messages, and the success block is executed, but I never get an email. any help would be much appreciated
my java script function
$('#ajax-contact').submit(function(event){
console.log(event)
event.preventDefault();
var firstname = $('#fname');
var lastname = $('#lname');
var subject = $('#subject');
var body = $('#body');
console.log(firstname);
console.log(lastname);
console.log(subject);
console.log(body);
$.ajax({
method: "POST",
URL: "send_mail.php",
data: "firstname=" + firstname + "&lastname=" + lastname + "&subject=" + subject + "&body=" + body,
success: function(){
$("#ajax-contact").trigger("reset");
window.alert("Message Successfully Sent");
}
});
});
and the php file
<?php
$to = "xxxxxxx";
$subject = $_POST["subject"];
$body = "Message from ".$_POST["firstname"]." ".$_POST["lastname"]." \r\n ".$_POST['body'];
if (mail($to, $subject, $body)) {
echo('Email successfully sent!');
return("success");
} else {
echo('Error Failed...');
return("Error");
}
?>
urlnotURLdataparameters properly in case they contain special characters. The best way to do that is to pass an object, which jQuery will encode automatically. If not, you need to callencodeURIComponent(body).