I am attempting to send the collected value's of a html form as an email to myself via PHP & Ajax. For some reason, I am able to update the UI with a success alert, however there's no actual email sent when I check my inbox. I am under the impression that my PHP script may be ill-structured, because when I log the results of my js function, all of the form values have been correctly captured.
Here is the JS:
function _(id){ return document.getElementById(id); };
function submitForm(){
var formdata = new FormData();
formdata.append( "first-name", _("first-name").value );
formdata.append( "last-name", _("last-name").value );
formdata.append( "email", _("email").value );
formdata.append( "subject", _("subject").value );
formdata.append( "message", _("message").value );
var ajax = new XMLHttpRequest();
ajax.open( "POST", "email_me.php" );
ajax.onreadystatechange = function() {
if(ajax.readyState == 4 && ajax.status == 200) {
if(ajax.responseText == "success"){
alert("Hey! It Worked!!");
} else {
// display error
}
}
}
ajax.send( formdata );
// Display the key/value pairs
for (var pair of formdata.entries()) {
console.log(pair[0]+ ', ' + pair[1]);
}
}
And Here is the php script (email_me.php file)
<?php
if(isset($_POST['first-name'], $_POST['last-name'], $_POST['email'], $_POST['subject'], $_POST['message'])){
$name = $_POST['first-name'];
$email = $_POST['email'];
$m = nl2br($_POST['message']);
$to = "me@gmail.com";
$from = $email;
$subject = $_POST['subject'];
$message = '<p>'.$m.'</p>';
$headers = "From: $from\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\n";
if( mail($to, $subject, $message, $headers) ){
echo "success";
} else {
echo "The server failed to send the message. Please try again later.";
}
}
?>
What seem's to be the issue? Im running the current version of Apache with a localhost, using MAMP Pro btw.
Here are the server logs:
Marker - Aug 23, 2016, 12:34:32 PM
Aug 23 12:35:24 MacBookAir postfix/master[7884]: daemon started -- version 2.11.0, configuration /etc/postfix Aug 23 12:36:24 MacBookAir postfix/master[7884]: master exit time has arrived
Aug 23 12:36:24 MacBookAir postfix/master[7885]: daemon started -- version 2.11.0, configuration /etc/postfix Aug 23 12:37:24 MacBookAir postfix/master[7885]: master exit time has arrived Aug 23 12:37:24 MacBookAir r postfix/master[7886]: daemon started -- version 2.11.0, configuration /etc/postfix