Contact form sends blank emails - php

My contact form is not including message and other informations in emails.
There is 'Unknown sender' and 'No subject'. Email contains my tags (from:, subject:, message:) but no content is written after them.
I have tried a few other scripts, but they gave the same result.
My JS code
(function($){
$(document).ready(function() {
$('#submit-form').click(function(e){
e.preventDefault();
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var name = $('#rp_name').val(),
email = $('#rp_email').val(),
subject = $('#rp_subject').val(),
message = $('#rp_message').val(),
data_html,
success = $('#success');
if(name === ""){
$('#rp_name').val('Please enter your name.');
}
if(subject === ""){
$('#rp_subject').val('Please enter your name.');
}
if(email === ""){
$('#rp_email').val('Your email is required.');
}else if(reg.test(email) === false){
$('#rp_email').val('Invalid Email Address.');
}
if(message === ""){
$('#rp_message').val('Message is required.');
}
if(message !== "" && name !== "" && reg.test(email) !== false) {
data_html = "name=" + name + "&email="+ email + "&message=" + message + "&subject="+ subject;
alert(data_html);
$.ajax({
type: 'POST',
url: 'php_helpers/contact_form.php',
data: data_html,
success: function(msg){
if (msg == 'sent'){
success.html('<div class="alert alert-success">Message <strong>successfully</strong> sent!</div>') ;
$('#rp_name').val('');
$('#rp_email').val('');
$('#rp_message').val('');
}else{
success.html('<div class="alert alert-error">Message <strong>not</strong> sent! Please Try Again!</div>') ;
}
}
});
}
return false;
});
});
})(jQuery);
My PHP code
<?php
$to = 'email'; // I changed it
$subject = $_POST['subject'];
if($to) {
$name = $_POST['name'];
$email = $_POST['email'];
$fields = array(
0 => array(
'text' => 'Imie',
'val' => $_POST['name']
),
1 => array(
'text' => 'Email',
'val' => $_POST['email']
),
2 => array(
'text' => 'WIADOMOSC',
'val' => $_POST['message']
)
);
$message = "";
foreach($fields as $field) {
$message .= $field['text'].": " . htmlspecialchars($field['val'], ENT_QUOTES) . "<br>\n";
}
$$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
$headers .= 'From: '. $email . "\r\n" . 'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
if ($message){
echo 'sent';
}else{
echo 'failed';
}
} else {
echo "Don't access this file directly";
}
?>
I'll be glad for any hints.

There as i check your contact.php file code is ok. But you need one thing if use firefox. please console your code.I mean when you open firebug there will be one option console. with help you can check is your value along with variable is going or they empty.
I think your value is not going to PHP file. use console and you can easily bug your value.
I hope this make sense for you.

Check if your php script receives name, email and message. You can check it using
var_dump($_POST);
If server doesn't receive these variables, try to send data_html as an object:
change
data: data_html,
to
data: {name: name, email: email, message: message}
I didn't test it, but I always use this way of sending data from js to server.

You are using two dollar symbols in the line: $$headers = 'MIME-Version: 1.0' . "\r\n"; Please remove "$" and try again.

Thanks for all your responses. I finally manage to find a solution. I haven't used firebug before, but thanks to it I could find the error message. Now the script is working fine.
It wasn't in code, but in .htaccess rewrite rule for .php files which was couseing 301 error for ajax request (../contact instead of ../contact.php).
I have one .php page (file uploader) and I thought that adding another seo-friendly link rule for it would be a good idea.

Related

PHP cancel redirection after script execution

I have a simple POST script for PHP which sends an email, but when I click the submit button it executes and then goes to the script directory (ex: localhost/sendMail/test.php). Is it possible to post an alert box, and then stay on the page instead of going to the script and then redirecting back onto the submit page?
This is my script.
<?php
$subject = 'Your website: Contact'; // Subject of your email
$to = 'myemail'; // Enter recipient's E-mail address
$emailTo = $_REQUEST['email'];
$headers = "MIME-Version: 1.1";
$headers .= "Content-type: text/html; charset=iso-8859-1";
$headers .= "From: " . $emailTo . "\r\n"; // Sender's E-mail
$headers .= "Return-Path:". $emailTo;
$body = 'You have received a new inquiry!' . "\n\n";
$body .= 'Name: ' . $_REQUEST['name'] . "\n";
$body .= 'Email: ' . $_REQUEST['email'] . "\n";
$body .= 'Phone: ' . $_REQUEST['phone'] . "\n\n";
$body .= 'Message: ' . $_REQUEST['message'];
if($_REQUEST['name'] != "" && $_REQUEST['email'] != "" && $_REQUEST['phone'] != "" && $_REQUEST['message'] != "")
{
if (#mail($to, $subject, $body, $headers))
{
// Transfer the value 'sent' to ajax function for showing success message.
echo 'sents';
}
else
{
// Transfer the value 'failed' to ajax function for showing error message.
echo 'failed';
}
}
else
{
$message = "Invalid fields!";
echo "<script type='text/javascript'>alert('$message');</script>";
//header("Location: http://localhost/abtek/contact.html");
exit;
}
?>
So when the alert is executed, is it possible to stop it from going to the script, and instead staying on the page until the fields are all valid to submit? As well as when they are submitted to display an alert again and stay on the page instead of doing a bunch of redirects.
Any help would be greatly appreciated.
You can submit the form with ajax/jquery and stop the redirect. See here: Stackoverflow
You can use jQuery, like this:
$('#my-submit').on('click', function(e){
e.preventDefault(); // prevents regular form submission
$.ajax({
url: 'localhost/sendMail/test.php',
data: $('form').serialize(),
success: function(result){
alert('Message: ' + result );
},
error: function(err){
alert(err)
}
})
});
In your PHP you should just do echo $message; to handle error better.
Read all you can about jQuery/AJAX, as there are important options you can explode, like using JSON.

Cannot send email using mail function

First question and first time looking at PHP so please bear with me.
I currently have the below jQuery which is calling a php file:
$(document).on('click', '#btnContactUs', function () {
var name = $("input#name").val();
var email = $("input#email").val();
var subject = $("input#subject").val();
var message = $("input#message").val();
var dataString = 'name='+ name + '&email=' + email + '&subject=' + subject + '&message=' + message;
$.ajax({
type: "POST",
url: "php/message.php",
data: dataString,
success: function(response) { alert(response); }
});
return false;
});
The console is logging the call as successful (XHR finished loading: POST "php/message.php").
Below is the full script in the file:
<?php
$to = 'nobody#example.com';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: webmaster#example.com' . "\r\n" .
'Reply-To: webmaster#example.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
?>
The email is not being sent/received (I am checking Spam also).
The files are hosted on a web server which has PHP installed. The alert box is popping up, but empty. The initial AJAX call is made from a submit button on a webpage.
EDIT: I am sending this to my personal email, which I have not included above.
EDIT: Even when visiting the URL of the script the email is still not being sent.
FINAL EDIT: The resolution is that my server did not have PHP mail installed - it is not supported as it is considered unreliable and therefore they recommend SMTP. To figure this out I used DrewT's solution of using SSH to check for "which sendmail"
Hope this scenario helps someone in the future.
Thanks all.
What seems to be happening is you are not sending your information in the correct format because you don't parse your var dataString on the server. I would try something like:
var name = $("input#name").val();
var email = $("input#email").val();
var subject = $("input#subject").val();
var message = $("input#message").val();
Then in your post function:
$.ajax({
type: "POST",
url: "php/message.php",
data : { name: name, email: email, subject: subject, message: message },
success: function (response, status, err) {
// do stuff...
// NOTE: don't return false or it won't send
// 'return false' only if the form is incomplete
// and you don't want the email sent out prematurely
}
});
Then to receive these vars in your PHP:
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
Now you can send an email like this:
// Enter your send email address
$to = 'email#example.com';
// Add your headers
$header = "from: $name <$email>";
// only send it if we have all the data we need
if( $subject !== "" || " " && $message !== "" || " " && $name !== "" || " " && $mail_from !== "" || " " ) {
$send_contact = mail($to,$subject,$message,$header);
// check if message was sent
// and provide some formatting (html) to send along in our response
if ($send_contact) {
echo '<div class="msg-sent">
Your message was sent successfully yay!
</div>';
}
else {
echo '<div class="msg-send-failed">
SEND FAILED :0
</div>';
}
}
else {
echo '<div class="msg-had-empty">
YOU HAD EMPTY POST VARIABLES :0
</div>';
}
Beyond that you will need to debug using the networks tab in your browser's inspector./ good luck!

Sending Email via PHP Not Working

I have a site running on Windows Azure that contains a simple contact form for people to get in touch. Unfortunately, that form isn't work right now...
I have an index.php file that contains the form:
<div class="form">name="name" placeholder="Name" id="contactname" />
<input type="text" name="email" placeholder="Email" id="contactemail" />
<textarea name="message" placeholder="Message" id="contactmessage"></textarea>
<button>Contact</button>
</div>
I then have a JS file like this:
if ($('#contact').is(":visible")) {
$("#contact button").click(function() {
var name = $("#contactname").val();
var message = $("#contactmessage").val();
var email = $("#contactemail").val();
var emailReg = /^[a-zA-Z0-9._+-]+#[a-zA-Z0-9-]+\.[a-zA-Z]{2,4}(\.[a-zA-Z]{2,3})?(\.[a-zA-Z]{2,3})?$/;
// client-side validation
if(emailReg.test(email) == false) {
var emailValidation = false;
$('#contactemail').addClass("error");
}
else
$('#contactemail').removeClass("error");
if(name.length < 1) {
var nameValidation = false;
$('#contactname').addClass("error");
}
else
$('#contactname').removeClass("error");
if(message.length < 1) {
var messageValidation = false;
$('#contactmessage').addClass("error");
}
else
$('#contactmessage').removeClass("error");
if ((nameValidation == false) || (emailValidation == false) || (messageValidation == false))
return false;
$.ajax({
type: "post",
dataType: "json",
url: "send-email.php",
data: $("#contact").serialize(),
success: function(data) {
$('.form').html('<p class="success">Thanks for getting in touch - we\'ll get back to you shortly.</p>');
}
});
return false;
});
};
and finally, a php file to send the email called send-email.php:
$destination = 'info#clouddock.co'; // change this to your email.
// ##################################################
// DON'T EDIT BELOW UNLESS YOU KNOW WHAT YOU'RE DOING
// ##################################################
$email = $_POST['email'];
$name = $_POST['name'];
$message = $_POST['message'];
$subject = $name;
$headers = "From: ".$name." <".$email.">\r\n" .
"Reply-To: ".$name." <".$email.">\r\n" .
"X-Mailer: PHP/" . phpversion() . "\r\n" .
"MIME-Version: 1.0\r\n" .
"Content-Type: text/plain; charset=\"iso-8859-1\r\n" .
"Content-Transfer-Encoding: 8bit\r\n\r\n";
mail($destination, $subject, $message, $headers);
}
When I fill in the contact form, the JS validation appears to be working, and when I click send the 'Thanks for getting in touch...' text appears, as if the message has been sent. But I don't receive any email. Can anyone advise as to where the problem might be? Could it be Azures configuration blocking the messages from being sent out?
You are using $("#contact").serialize() to get data to send but you've got no elements with ID contact.
You should use $("#contactname, #contactemail, #contactmessage").serialize() (and fix first input ;) ).
And always validate input data in PHP, not only in JS!
Of course it will display the thanks message, all it needs is a response back from the server. What you need is to test whether the mail actually sent or not, then return that back to your original script to determine what message to show.
if(mail($destination, $subject, $message, $headers)) {
return '<p class="success">Thanks for getting in touch - we\'ll get back to you shortly.</p>';
} else {
return '<p class="fail">The e-mail failed to send.</p>';
}
And then set your AJAX to:
$.ajax({
type: "post",
url: "send-email.php",
data: $("#contact").serialize(),
success: function(data) {
$('.form').html(data);
}
});
You'll probably find that you get the fail message, and that could well be the setup of your server, or it could be you not passing the right thing to the mail() function. You then need to debug your script to find out whether the right information is being passed etc.
With Windows servers they need to be configured to pass all mail from the mail() function to an SMTP server, so if that's not been done on your Azure server then your mail will instantly fail.

Contact from, PHP doesn't return string to AJAX

I have AJAX contact form on my hosting server and mail.php file on different domain (another hosting). I am trying to validate a form with jQuery and send email using AJAX, but when I call php file, it sends email to mail email box, but doesn't return a 'success' message. Instead I get "an empty string".
I have in js
$.ajax({
type: 'POST',
url: options.url,
data: {subject:options.subject, name:$('#name').val(), email:$('#email').val(), message:$('#message').val()},
success: function(data){
if( data == 'success') {
$('#callback').append(options.recievedMsg);
} else {
$('#callback').append(options.notRecievedMsg);
}
});
And php looks like this
<?php
define( "RECIPIENT_NAME", "John Smith" );
define( "RECIPIENT_EMAIL", "my.email#mail.com" );
define( "EMAIL_SUBJECT", "Visitor Message" );
$senderName = stripcslashes($_POST['name']);
$senderEmail = stripcslashes($_POST['email']);
$message = stripcslashes($_POST['message']);
if ( $senderName && $senderEmail && $message ) {
$recipient = RECIPIENT_NAME . " <" . RECIPIENT_EMAIL . ">";
$headers = "From: " . $senderName . " <" . $senderEmail . ">";
$success = mail( $recipient, EMAIL_SUBJECT, $message, $headers );
};
echo 'success';
?>
When I check in console 'data' value it says (an empty string) and in ajax if function I always get false and notReceived message.
How can I make php file to return 'success' that if(data == 'success') state would be true? Am I missing sometehing here?
You can't send an AJAX request to another domain because of the same-origin policy.

Can I reset a form with PHP?

is possible to use php to reset a form without refresh?
how can i archive this?
or is possible to do it with js?
most important is do it without to refresh the page and dont add another button for this(that's because the design)
any idea?
thanks
am working with recaptcha on my form and once i submitted the information i want to send a message
this is my js code
function validateCaptcha(){
challengeField = $("input#recaptcha_challenge_field").val();
responseField = $("input#recaptcha_response_field").val();
nameField = $("input#name").val();
emailField = $("input#email").val();
phoneField =$("input#phone").val();
reasonField =$("select#reason").val();
messageField =$("textarea#message").val();
var html = $.ajax({
type: "POST",
url: "ajax.recaptcha.php",
data: "recaptcha_challenge_field=" + challengeField + "&recaptcha_response_field=" + responseField +"&name="+ nameField +"&email=" + emailField +"&phone="+ phoneField + "&reason=" + reasonField +"&message=" + messageField,
async: false
}).responseText;
if(html == "success")
{
$("#captchaStatus").html("Success. Submitting form.");
$("#thanks").html("Thank you, we going to keep in touch with you soon. ");
return false;
}
else
{
$("#captchaStatus").html("Your captcha is incorrect. Please try again");
Recaptcha.reload();
return false;
}
}
this is my php code
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$reason = $_POST['reason'];
$message = $_POST['message'] ;
if (empty($name)|| empty($email) || empty($message))
{
}
else
{
$resp = recaptcha_check_answer (PRIVATEKEY, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]);
if ($resp->is_valid) {
$header = 'From: ' . $email . " \r\n";
$msg = "Sent from: " . $name . "\r\n";
$msg .= "Email: " . $email . " \r\n";
$msg .= "Phone: " . $phone . " \r\n";
$msg .= "Contact reason:" . $reason . " \r\n";
$msg .= "Message: " . $message . " \r\n";
$to = 'patricia#anetdesign.com';
$subject = 'Emailmakers contact page';
mail($to, $subject, utf8_decode($msg), $header);
?>success<?
}
else
{
die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." .
"(reCAPTCHA said: " . $resp->error . ")");
}
}
Well, once you sed the ajax request if the captcha fails then just reload the entire form.
Say you have only the form in myform.php and you include it in your main page, when the captcha does not match you can just reload the form. Like this:
if (html != "Success")
{
$("#divThatHoldsTheForm").html(html)
}
and in your myform.php you have only:
<form action="..." method="POST">
<!-- some inputs -->
</form>
Use the reset() function. If you have a form named frm then use can use frm.reset().
Or just write code to first get all textboxes and set its value attribute to "". this wont need to refresh your page
Using PHP mean refreshing the page (only in case of ajax) so i suggest you try to use javascript instead of php to this task

Categories