display error from jquery post - php

i am posting to a mailer.php file.
mailer.php
<?php
if(isset($_POST['submit'])) {
$to = "testabc#gmail.com";
$subject = "Contact via website";
$name_field = $_POST['name'];
$email_field = $_POST['email'];
$message = $_POST['message'];
$body = "From: $name_field\n E-Mail: $email_field\n Message:\n $message";
echo "Data has been submitted to $to!";
mail($to, $subject, $body);
} else {
echo "blarg!";
}
?>
here is my js code
$('.submit').click(function(){
$('span.msg').css({'visibility': 'visible'}).text('Sending...');
$.post("mailer.php", $(".contactPage").serialize(),
function(data){
$('span.msg').text('Your Message has been received. Thank you').show();
});
return false;
});
I am getting message of success but email is not received. What i am doing wrong? How to get error detail from mailer.php file and showing in span.msg?

if(mail($to, $subject, $body)){
echo "success";
}else{
echo "fail";
}
JS:
$('.submit').click(function(){
$('span.msg').css({'visibility': 'visible'}).text('Sending...');
$.post("mailer.php", $(".contactPage").serialize(),
function(data){
if(data == 'success'){
$('span.msg').text('Your Message has been received. Thank you').show();
}else{
$('span.msg').text('Your Message has failed. Thank you').show();
}
});
return false;
});

On this page under the Return Values section it says:
Returns TRUE if the mail was successfully accepted for delivery, FALSE otherwise.
It is important to note that just because the mail was accepted for delivery, it does NOT mean the mail will actually reach the intended destination.
So just check if it is returning true or false.
EDIT: Also try checking your spam folder. Perhaps someone on your shared hosting provider is sending spam.

Related

Validate full contact page

<?php
if (isset($_POST["sendMessage"])) {
$firstName = trim($_POST['firstName']);
$lastName = trim($_POST['lastName']);
$email = trim($_POST['email']);
$phone = trim($_POST['phone']);
$message = trim($_POST['message']);
$from = 'somebody#gmail.com';
$to = 'someone#gmail.com';
$subject = 'webmaster#example.com';
$txt = 'Prottyasha School';
$headers = "From: somebody#gmail.com" . "\r\n" .
"CC: somebody#gmail.com";
$body = "From: First-Name: $firstName\n Last-Name: $lastName\n
E-Mail: $email\n Phone: $phone\n Message: $message";
//echo "success?";
if (mail($to, $subject, $body, $headers)) {
$result = '<div class="alert alert-success">Thank You! I will be in touch</div>';
} else {
$result = '<div class="alert alert-danger">Sorry there was an error sending your message. Please try again later</div>';
}
echo $result;
}
?>
It works fine but i want to make it validated. suppose someone give a invalid phone number or email then it will message its invalid mail or phone number. i want to make it full validated. anyone please help me.
I don't think it's possible to check if the mail was successfully delivered. mail() returns boolean true when a mail has been accepted for delivery or sent to the local email service. There's no way to know if that email was delivered to the recipient.

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';
}
})

AJAX jquery form submitting an error message

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."

Send mail from website ubuntu, php, ajax

I have a website with a form where you can send a message to my email adress. But it doesn't work yet. I am not really sure what is required to do this. Here is what i have done so far:
The PHP:
<?php
if (isset($_POST['from']) && isset($_POST['header']) && isset($_POST['message'])) {
$to = "example#awesomemail.com";
$subject = $_POST['from'];
$body = $_POST['message'];
$headers = $_POST['header'];
if (mail($to, $subject, $body, $headers)) {
echo("<p>Email successfully sent!</p>");
echo json_encode('success');
} else {
echo("<p>Email delivery failed…</p>");
echo json_encode('failed');
}
}
?>
The JS:
$.ajax({
type : "POST",
url : "sendmail.php",
data: {"from": from, "header": header, "message": message},
dataType: "json",
success: function(msg){
alert(msg);
}
});
Is there something wrong with my code or am i missing something?
The email is supposed to be sent to a gmail account.
Not enough points to comment on question... but just wanted to confirm you have an Mail Transfer Agent set up on the system. If not, that may be the culprit.
If this hasn't yet been done yet, you can refer to sendmail: how to configure sendmail on ubuntu? or https://help.ubuntu.com/12.04/installation-guide/i386/mail-setup.html to get that going.
Try it like this , try sending a complete json response from the server side to client side for it to parse..
PHP :
<?php
if (isset($_POST['from']) && isset($_POST['message']))
{
$to = "example#awesomemail.com";
$subject = $_POST['from'];
$body = $_POST['message'];
$headers = urldecode($_POST['header']);
if (mail($to, $subject, $body, $headers))
echo json_encode('success');
else
echo json_encode('failed');
}
else
echo json_encode('failed');
?>
JS :
$.post('sendmail.php',{"from": from ,"header" :header, "message":message},function(response)
{
var response = $.parseJSON(response);
console.log(response);
});
if sending header is a problem you can do like this:
first concat all values into one variable
var string = 'mail='+from+'/'+header+'/'+message;
$.ajax({
type : "POST",
url : "sendmail.php",
data: string,
dataType: "json",
success: function(msg){
alert(msg);
}
});
sendmail.php
<?php
if (isset($_POST['mail']) && !empty($_POST['mail'])) {
$msg = explode('/','$_POST['mail']');
$to = "example#awesomemail.com";
$subject = $msg[0];
$headers = $msg[1];
$body = $msg[2];
if (mail($to, $subject, $body, $headers)) {
echo("<p>Email successfully sent!</p>");
echo json_encode('success');
} else {
echo("<p>Email delivery failed…</p>");
echo json_encode('failed');
}
}
?>
This answer is just another alternative way, more based on your comment.
(you can perform javascript validation before submitting form or with condition before even entering jquery/ajax)

php sending email

mailer.php
<?php
if(isset($_POST['submit'])) {
$to = "abc#gmail.com";
$subject = "Contact via website";
$name_field = $_POST['name'];
$email_field = $_POST['email'];
$message = $_POST['message'];
$body = "From: $name_field\n E-Mail: $email_field\n Message:\n $message";
echo "1";
echo "Data has been submitted to $to!";
mail($to, $subject, $body);
} else {
echo "0";
}
?>
jquery code
$('.submit').click(function(){
$('span.msg').css({'visibility': 'visible'}).text('Sending...');
$.post("mailer.php", $(".contactPage").serialize(),
function(data){
$('span.msg').text((data == "1") ? 'Your Message has been received. Thank you' : "Could not send your message at this time").show();
});
return false;
});
I am always getting
Could not send your message at this time
I have almost no knowledge in php, whats i am doing wrong?
Your php script never prints just 1 it prints 0 or 1Data has been submitted to... thus (data == "1") can never be true.
btw: Your script could at least use the return value of mail() to decide whether it signals success or failure.
First of all, check server's mail settings. If your script resides on a server, which you don't administer, the simplest way is to do this is creating a simple PHP file with the following content:
<?php
mail("youraccount#example.com","test","works"); <br>
?>
Run it and check your e-mail.

Categories