How should I properly structure this PHP mailing script? - javascript

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

update you php code and check it will work
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']);
$message = '<p>Name => '.$name.' <br/> Email =>'.$email.'<br /> Message =>'.$m.'</p>';
$to = "me#gmail.com";
$subject = $_POST['subject'];
$headers = "From: noreply#something.com\r\n"; // use \r\n
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\r\n"; // use \r\n
$headers.= "X-Priority: 1\r\n";
if( mail($to, $subject, $message, $headers) ){
echo "success";
} else {
echo "The server failed to send the message. Please try again later.";
}
}

Related

Angular 'Uncaught error: Zone already loaded'

Errors in console
I am using a Mailchimp Ajax Submit jQuery Plugin to submit an email using a PHP file on a contact form in a website template I imported to my Angular app. When I go to enter my details on the form and submit, the page refreshes on the POST request.
The console then throws the following two errors.
[Deprecation] Synchronous XMLHttpRequest
[Deprecation] Synchronous XMLHttpRequest
on the main thread is deprecated because of its detrimental effects to the
end user's experience. For more help, check https://xhr.spec.whatwg.org/.
(anonymous) # polyfills.c5fb4ffca9c225046d5a.js:1
polyfills.c5fb4ffca9c225046d5a.js:1
Uncaught Error: Zone already loaded.
Uncaught Error: Zone already loaded.
at polyfills.c5fb4ffca9c225046d5a.js:1
at polyfills.c5fb4ffca9c225046d5a.js:1
at Object.0TWp (polyfills.c5fb4ffca9c225046d5a.js:1)
at p (<anonymous>:1:507)
at Object.hN/g (polyfills.c5fb4ffca9c225046d5a.js:1)
at p (<anonymous>:1:507)
at Object.5 (polyfills.c5fb4ffca9c225046d5a.js:1)
at p (<anonymous>:1:507)
at n (<anonymous>:1:376)
at e (<anonymous>:1:248)
I am finding it difficult to understand the cause of the problem. I have tried to prevent the page from refreshing on submit using <button type="button">, this does not do a page refresh however it does not call a POST request as expected.
I have also tried un-commenting import 'zone.js/dist/zone'; in polyfills.ts
I wish to accomplish sending the email on the same page without a refresh in the Angular app unless there is a better alternative. (I am learning)
main.js
var clContactForm = function() {
/* local validation */
$('#contactForm').validate({
/* submit via ajax */
submitHandler: function(form) {
var sLoader = $('.submit-loader');
$.ajax({
type: "POST",
url: "inc/sendEmail.php",
data: $(form).serialize(),
beforeSend: function() {
sLoader.slideDown("slow");
},
success: function(msg) {
// Message was sent
if (msg == 'OK') {
sLoader.slideUp("slow");
$('.message-warning').fadeOut();
$('#contactForm').fadeOut();
$('.message-success').fadeIn();
}
// There was an error
else {
sLoader.slideUp("slow");
$('.message-warning').html(msg);
$('.message-warning').slideDown("slow");
}
},
error: function() {
sLoader.slideUp("slow");
$('.message-warning').html("Something went wrong. Please try again.");
$('.message-warning').slideDown("slow");
}
});
}
});
};
sendEmail.php
<?php
// Replace this with your own email address
$siteOwnersEmail = 'my-email';
if($_POST) {
$name = trim(stripslashes($_POST['contactName']));
$email = trim(stripslashes($_POST['contactEmail']));
$subject = trim(stripslashes($_POST['contactSubject']));
$contact_message = trim(stripslashes($_POST['contactMessage']));
// Check Name
if (strlen($name) < 2) {
$error['name'] = "Please enter your name.";
}
// Check Email
if (!preg_match('/^[a-z0-9&\'\.\-_\+]+#[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is', $email)) {
$error['email'] = "Please enter a valid email address.";
}
// Check Message
if (strlen($contact_message) < 15) {
$error['message'] = "Please enter your message. It should have at least 15 characters.";
}
// Subject
if ($subject == '') { $subject = "Contact Form Submission"; }
// Set Message
$message .= "Email from: " . $name . "<br />";
$message .= "Email address: " . $email . "<br />";
$message .= "Message: <br />";
$message .= $contact_message;
$message .= "<br /> ----- <br /> This email was sent from your site's contact form. <br />";
// Set From: header
$from = $name . " <" . $email . ">";
// Email Headers
$headers = "From: " . $from . "\r\n";
$headers .= "Reply-To: ". $email . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
if (!$error) {
ini_set("sendmail_from", $siteOwnersEmail); // for windows server
$mail = mail($siteOwnersEmail, $subject, $message, $headers);
if ($mail) { echo "OK"; }
else { echo "Something went wrong. Please try again."; }
} # end if - no validation error
else {
$response = (isset($error['name'])) ? $error['name'] . "<br /> \n" : null;
$response .= (isset($error['email'])) ? $error['email'] . "<br /> \n" : null;
$response .= (isset($error['message'])) ? $error['message'] . "<br />" :
null;
echo $response;
} # end if - there was a validation error
}
?>

500 Internal Server Error (Contact Form, PHP)

We are running a website on a local server. After entering the required data into contact form and clicking the button Send, we get the "500 Internal Server Error". I'm assuming this relates to PHP mail configuration for local servers.
PHP:
<?php
if(isset($_POST["name"]) && isset($_POST["email"]) && isset($_POST["msg"])){
$name = $_POST["name"];
$email = $_POST["email"];
$subject = $_POST["subject"];
$msg = nl2br($_POST["msg"]);
$to = "info#companyname.com";
$from = $email;
$message = "<b>Name:</b> ".$name." <br><b>E-mail:</b> ".$email." <br><b>Subject:</b> ".$subject." <br><p> ".$msg." </p>";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= "From: $from" . "\r\n";
if(mail($to, $subject, $message, $headers)){
echo "Success";
}else{
echo "The server failed to send the message. Please try again later.";
}
}
?>
JS:
function _(id){return document.getElementById(id);}
function submitForm(){
_("submit").disabled = true;
_("status").innerHTML = "Please wait...";
var formdata = new FormData();
formdata.append("name", _("name").value);
formdata.append("email", _("email").value);
formdata.append("subject", _("subject").value);
formdata.append("msg", _("msg").value);
var ajax = new XMLHttpRequest();
ajax.open("POST", "contact.php");
ajax.onreadystatechange = function(){
if(ajax.readyState == 4 && ajax.status == 200){
if(ajax.responseText == "Success"){
_("status").innerHTML = "";
_("response").innerHTML = "Your message has been successfully sent.";
}else{
_("status").innerHTML = ajax.responseText;
_("submit").disabled = false;
}
}
}
ajax.send(formdata);
}
I think your problem is caused by SMTP server configuration. There are no syntax errors in the code. If the php would be in wrong folder it would return 404 error not 500.
Try to comment the if/else part of the php file just to make sure the other parts of the file are working.
Solved. The problem was with the configuration of our local server which runs on MS IIS.

Facebook javascript api - webhook

i am having a problem to do a webhook with the facebook api on a lead ads form.
Last day it was working like a charm. On the 'Lead Ads Testing Tool' i received a status = success. Now i received a status = failure, error code = 102, error message = server failure
image of the error 102
Anyone know this issue ?
here my webhook.php :
if (isset($_GET['hub_verify_token'])) {
if ($_GET['hub_verify_token'] === 'your verify token') {
echo $_GET['hub_challenge'];
return;
} else {
echo 'Invalid Verify Token';
return;
}
}
$input = json_decode(file_get_contents('php://input'), true);
$emailfrom = "test#test.com";
$emailto = "my#email.com";
$subject = "You've got a new submission Test";
$headers = "From: " . $emailfrom . "\r";
$headers .= "Reply-To: ". $emailfrom . "\r";
$headers .= "MIME-Version: 1.0\r";
$headers .= "Content-Type: text/html; charset=utf-8\r";
$body = 'hello';
mail($emailto, $subject, $body, $headers);
and the callback_url is good = "success": true image graph api subscription to webhook
Thanks

user enters name before quiz starts using javascript

I have created a quiz but would like to know how to start when making a user input to email.
Basically I would like the user to enter their name before they start my quiz and then once they have finished the quiz the results get sent to me by email using Javascript.
Is this possible?
You can't send email with plain JavaScript as far as I know, you will need to have a service, backend or a php file..
for example this php file:
<?php
header('Content-type: application/json');
$errors = '';
if(empty($errors))
{
$from_name = $_POST['name'];
$from_email = $_POST['email'];
$message = $_POST['message'];
$to_email = 'your#email.com';
$to_email_cc = $from_email;
$contact = "<p><strong>Name:</strong> $from_name</p>
<p><strong>Email:</strong> $from_email</p>";
$content = "<p>$message</p>";
$email_subject = "Neue Nachricht von $from_name erhalten";
$email_subject_cc = "Deine Nachricht wurde gesendet";
$email_body = '<html><body>';
$email_body .= "$contact $content";
$email_body .= '</body></html>';
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$headers .= "From: $my_email\n";
$headers .= "Reply-To: $from_email";
mail($to_email,$email_subject,$email_body,$headers);
mail($to_email_cc,$email_subject_cc,$email_body,$headers);
$response_array['status'] = 'success';
echo json_encode($response_array);
} else {
$response_array['status'] = 'error';
echo json_encode($response_array);
}
?>
and then you could do a post on that with for example angular, jquery or other..
something like this:
postEmail(newMail: Email): Observable<string>{
let body = `name=${newMail.name}&email=${newMail.email}&message=${newMail.message}`;
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
let options = new RequestOptions({ headers: headers });
return this._http.post(this._contactUrl, body, options)
//.map(res => <string> res.json())
.catch(this.handleError)
}
this is some old code from angular2 i wrote once and is not tested, but it should give you an idea of how to do it.

PHP email issue with $Error message

On a Linux server, I have an ajax form that gets posted to a js script, which in turn posts to a php routine for sending a web site email contact form (Styleshout-Puremedia template). I know the post is occurring to js, and to the php page. I get an httpd server error on the php page that "$Error is undefined". However if I define it as NULL or '' it exists and therefore doesn't pass the test "if (!$Error)". If I create a hard-coded php script using the mail function, the e-mail works so php and sendmail are all configured properly. Can someone help as to why this php script doesn't work, or how to fix the "$Error" error?
PHP code:
<?php
// Replace this with your own email address
$siteOwnersEmail = 'info#mydomain.com';
if($_POST) {
$fname = trim(stripslashes($_POST['contactFname']));
$lname = trim(stripslashes($_POST['contactLname']));
$email = trim(stripslashes($_POST['contactEmail']));
$subject = trim(stripslashes($_POST['contactSubject']));
$contact_message = trim(stripslashes($_POST['contactMessage']));
// Check First Name
if (strlen($fname) < 2) {
$error['fname'] = "Please enter your first name.";
}
// Check Last Name
if (strlen($lname) < 2) {
$error['lname'] = "Please enter your last name.";
}
// Check Email
if (!preg_match('/^[a-z0-9&\'\.\-_\+]+#[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is', $email)) {
$error['email'] = "Please enter a valid email address.";
}
// Check Message
if (strlen($contact_message) < 15) {
$error['message'] = "Please enter your message. It should have at least 15 characters.";
}
// Subject
if ($subject == '') { $subject = "Contact Form Submission"; }
// Set Name
$name = $fname . " " . $lname;
// Set Message
$message = "Email from: " . $name . "<br />";
$message .= "Email address: " . $email . "<br />";
$message .= "Message: <br />";
$message .= $contact_message;
$message .= "<br /> ----- <br /> This email was sent from your site's contact form. <br />";
// Set From: header
$from = $name . " <" . $email . ">";
// Email Headers
$headers = "From: " . $from . "\r\n";
$headers .= "Reply-To: ". $email . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
if (!$error) {
ini_set("sendmail_from", $siteOwnersEmail); // for windows server
$mail = mail($siteOwnersEmail, $subject, $message, $headers);
if ($mail) { echo "OK"; }
else { echo "Something went wrong. Please try again."; }
} # end if - no validation error
else {
$response = (isset($error['fname'])) ? $error['fname'] . "<br /> \n" : null;
$response .= (isset($error['lname'])) ? $error['lname'] . "<br /> \n" : null;
$response .= (isset($error['email'])) ? $error['email'] . "<br /> \n" : null;
$response .= (isset($error['message'])) ? $error['message'] . "<br />" : null;
echo $response;
} # end if - there was a validation error
}
?>
Thanks for your help!!
-Rob
You can always just initialize $error as
$error = [];
and then check for errors by
if(count($errors) === 0){
//no errors
}
Or, just use if(!isset($error)){//no errors}

Categories