AJAX jquery form submitting an error message - php

I am trying to a Jquery Ajax contact form from treehouse's blog Click here i have tried to edit the form slight by removing the 'message field'. From the HTML and JS
I am receiving an error message after submitting my details in the form. Code pen link
Below is a snippet of my code.
HTML :
<form id="ajax-contact" class="main-contact submit-fade ajax-form" action="register.php" method="POST">
<ul class="small-block-grid-2 medium-block-grid-2 hide-form">
<li>
<label for="name">Name</label>
<input type="text" class="form-control" name="name" placeholder="Name" required>
</li>
<li>
<label for="email">Email</label>
<input type="text" class="form-control" name="email" placeholder="Email">
</li>
</ul>
<input type="submit" class="btn btn-success">
</form>
JS :
var form = $('#ajax-contact');
var formMessages = $('#form-messages');
$(form).submit(function(e) {
e.preventDefault();
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
// Set the message text.
$(formMessages).text(response);
// Clear the form.
$('#name').val('');
$('#email').val('');
//$('#message').val('');
})
.fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
});
PHP :
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$message = trim($_POST["message"]);
// Check that data was sent to the mailer.
if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
http_response_code(400);
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
// Set the recipient email address.
// FIXME: Update this to your desired email address.
$recipient = "hello#example.com";
// Set the email subject.
$subject = "New contact from $name";
// Build the email content.
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Message:\n$message\n";
// Build the email headers.
$email_headers = "From: $name <$email>";
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
http_response_code(200);
echo "Thank You! Your message has been sent.";
} else {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "Oops! Something went wrong and we couldn't send your message.";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>

Remove all message variables and conditions from php file.
Your code look like this:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
// Check that data was sent to the mailer.
if ( empty($name) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
http_response_code(400);
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
// Set the recipient email address.
// FIXME: Update this to your desired email address.
$recipient = "hello#example.com";
// Set the email subject.
$subject = "New contact from $name";
// Build the email content.
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n\n";
// Build the email headers.
$email_headers = "From: $name <$email>";
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
http_response_code(200);
echo "Thank You! Your message has been sent.";
} else {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "Oops! Something went wrong and we couldn't send your message.";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>

resolved the error ("Oops! Something went wrong and we couldn't send your message.") by setting read/write permission on /volume1/web/
Synology support response: "After checking with our developer, normally, using the PHP mail function won't need the write permission, and not sure why your website needs it.
Furthermore, please be aware that giving R/W permission could allow someone to write or even overwrite files in /web folder, or the subfolders."

Related

Contact form using PHP mail() responds with 500 error [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I'm trying to get a contact form using ajax and PHP to work but I'm getting a 500 error response every time. PHP isn't my strong point and I've spent hours trying to find the error in my code as I know there must be one. I've even tried linters but they're telling me it's all good.
JS
$(function() {
// Get the form.
var form = $('#ajax-contact');
// Get the response messages div.
var formMessages = $('#form-messages');
// Set up an event listener for the contact form.
$(form).submit(function(event) {
// Stop the browser from submitting the form.
event.preventDefault();
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
// Make sure that the form-messages div has the 'success' class.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
// Set the message text.
$(formMessages).text('Message sent. Expect a reply within 24 hours!');
// Clear the form.
$('#name').val('');
$('#email').val('');
$('#company').val('');
$('#message').val('');
})
.fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
// Set the message text if there's a respone
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
});
});
PHP
<?php
// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$company = strip_tags(trim($_POST["company"]));
$company = str_replace(array("\r","\n"),array(" "," "),$company);
$message = trim($_POST["message"]);
// Check that data was sent to the mailer.
if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
http_response_code(400);
echo "There was a problem with your submission. Please complete the form and try again.";
exit;
}
// Set the recipient email address.
$recipient = "jacob#business.co.uk";
// Set the email subject.
$subject = "New message from $name";
// Build the email content.
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n";
$email_content .= "Company: $company\n\n";
$email_content .= "Message:\n$message\n";
// Build the email headers.
$email_headers = "From: $name <$email>";
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
http_response_code(200);
echo "Thank You! Your message has been sent.";
} else {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "Something went wrong and your message couldn't be sent.";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>
In your code example you have a line saying
if (mail($recipient, $subject, $email_content, $email_headers)) {
And in case mail returns false it jumps down to the else statement saying this:
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "Something went wrong and your message couldn't be sent.";
I guess that your server doesn't have sendmail set up.
Try reading the server logs if you have access and/or use var_dump (or xdebug if you know how to use that) and print out your parameters like so:
if (mail($recipient, $subject, $email_content, $email_headers)) {
// ...
}
else {
var_dump( error_get_last() );
var_dump( $recipient );
var_dump( $subject );
var_dump( $email_content );
var_dump( $email_headers );
}
Further help on this topic: PHP mail form doesn't complete sending e-mail
PHP Mail

How do I redirect after success in php

I need some help with my php. I am creating an ajax php mailer system, and I'm trying to figure out two things, I want to make it so when the email is successfully sent, to redirect to another page
and, I have another problem, when I send an email, the 'from' part has a name of my web host username, and I want to change it to my email, anyone know how to do that with php, or ajax.
php file
<?php
// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$name = strip_tags(trim($_POST["name"]));
$phone = trim($_POST["tel"]);
$time = trim($_POST["time"]);
$method = trim($_POST["method"]);
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$message = trim($_POST["message"]);
// Check that data was sent to the mailer.
if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
http_response_code(400);
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
// Set the recipient email address.
// FIXME: Update this to your desired email address.
$recipient = "WebInquiry#ThePPCGroup.Com";
// Set the email subject.
$subject = "New contact from $name";
$msg = "Thank you for contacting ThePPCGroup.\nSomeone will contact you shortly. Please let us know the best time to reach you, and if phone or email is better.\nThePPCGroup\n855-539-4742\nWebInquiry#ThePPCGroup.Com\nWWW.ThePPCGroup.Com";
// Build the email content.
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Phone: $phone\n\n";
$email_content .= "Prefered Time: $time\n\n";
$email_content .= "Prefered Method: $method\n\n";
$email_content .= "Message:\n$message\n";
// Build the email headers.
$email_headers = "From: $name <$email>";
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
http_response_code(200);
mail($email, "Thank You!", $msg, "WebInquiry#ThePPCGroup.Com")
} else {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "Oops! Something went wrong and we couldn't send your message.";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>
ajax file
function sendEmail() {
var form = $('#ajax-contact');
var formMessages = $('#form-messages');
var formData = $(form).serialize();
$(form).submit(function(event) {
event.preventDefault();
});
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
$(formMessages).text(response);
$('#name').val('');
$('#email').val('');
$('#tel').val('');
$('#time').val('');
$('#method').val('');
$('#message').val('');
window.location = 'http://www.theppcgroup.com/thank-you.html';
})
.fail(function(data) {
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
}
if ($('#submit').on('click', function() {
sendEmail();
}));
You can return an array to the ajax function like this:
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
http_response_code(200);
mail($email, "Thank You!", $msg, "WebInquiry#ThePPCGroup.Com");
$response = array('status': true, 'message': "Thank You!");
} else {
// Set a 500 (internal server error) response code.
http_response_code(500);
$response = array('status': false, 'message': "Oops! Something went wrong and we couldn't send your message.");
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
$response = array('status': false, 'message': "There was a problem with your submission, please try again.");
}
return json_encode($response);
and in ajax
.done(function(response) {
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
$(formMessages).text(response.message);
$('#name').val('');
$('#email').val('');
$('#tel').val('');
$('#time').val('');
$('#method').val('');
$('#message').val('');
if (response.status == true){
window.location = 'http://www.theppcgroup.com/thank-you.html';
}
})

redirecting to thankyou page code check

The code below is form for mail..but em not able to redirect..can anyone check whats wrong in the code.. The thankyou.html is in the same folder.
Thanks in advance
`http://blog.teamtreehouse.com/create-ajax-contact-form
// Added input sanitizing to prevent injection
// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$message = trim($_POST["message"]);
$phone = trim($_POST["phone"]);
// Check that data was sent to the mailer.
if ( empty($name) OR empty($phone) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
http_response_code(400);
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
// Set the recipient email address.
// FIXME: Update this to your desired email address.
$recipient = "ranjith#appleete.com";
// Set the email subject.
$subject = "New contact from $name";
// Build the email content.
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Phone:\n$phone\n";
$email_content .= "Message:\n$message\n";
// Build the email headers.
$email_headers = "From: $name <$email>";
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
header('Location:thankyou.html');
}
else {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "Oops! Something went wrong and we couldn't send your message.";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>'
Make sure that the mail part works, so it's reaching the redirect part.
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
echo "It tries to redirect"; exit; //Do you see this!?
header('Location:thankyou.html');
exit; //Add an exit to make sure your code stops here.
}
Also make sure there isn't anything like echo, print_r, var_dump, or anything else that display things before the header part. It won't work when you already have output.
If this is called through an AJAX request you need to be aware that that the thankyou page echo the correct HTML and your AJAX callback function displays this HTML correctly.

PHP form POST working fine on ASO. Throws Internal Server Error (500) after migrating to Crazy Domains

I have a simple PHP form that was working fine on my ASO Hosting. After cloning the website on client hosting (Crazy Domains); it still sends the email perfectly but console is returning a 500 error. Any ideas?
<?php
// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
// Check that data was sent to the mailer.
if ( empty($name) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
http_response_code(400);
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
// Set the recipient email address.
$recipient = "example#gmail.com";
// Set the email subject.
$subject = "New contact from $name";
// Build the email content.
$email_content = "Name: $name\n";
$email_content .= "Email: $email";
// Build the email headers.
$email_headers = "From: $name <$email>";
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
http_response_code(200);
echo "Thank You! Your message has been sent.";
} else {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "Oops! Something went wrong and we couldn't send your message.";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>
Thanks in advance for any help!

Send ajaxform data to multiple email addresses

I wish to send a copy of the data filled out by the visitor to myself and the other copy to the visitor. Please advice!
My email is myemail#mysite.com while the visitor's email is $email
This code is as seen below:
// Set the recipient email address.
// FIXME: Update this to your desired email address.
$recipient = "myemail#mysite.com, .$email";
I'm not getting any results after hitting the submit button!
I'll be very grateful!
<?php
// My modifications to mailer script from:
// http://blog.teamtreehouse.com/create-ajax-contact-form
// Added input sanitizing to prevent injection
// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$message = trim($_POST["message"]);
// Check that data was sent to the mailer.
if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
http_response_code(400);
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
// Set the recipient email address.
// FIXME: Update this to your desired email address.
$recipient = "myemail#mysite.com, .$email";
// Set the email subject.
$subject = "New contact from $name";
// Build the email content.
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Message:\n$message\n";
// Build the email headers.
$email_headers = "From: $name <$email>";
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
http_response_code(200);
echo "Thank You! Your message has been sent.";
} else {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "Oops! Something went wrong and we couldn't send your message.";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>
You have to put myemail and visitors emails in one array and then run a loop, the same message will be send to all in array.
e.g.
$aEmails = array();
$aEmails[] = 'myemail#something.com';
$aEmails[] = 'visitoremail#something.com';
foreach(aEmails AS aEmail){
mail($aEmail, $subject, $email_content, $email_headers);
}
If you are not getting any result then you must check your html forms' tag it should have method="POST" attribute.
Then in here remove the dot
$recipient = "myemail#mysite.com, .$email";
like this
$recipient = "myemail#mysite.com, $email";

Categories