Website contact form not receiving messages - javascript

Very new html and website developer and unsure why my current contact box is not working. I'm hosting it my own website and when I do attempt to send I get a message sent response but the emails are never received.
I have't eliminated the email hosting being broken by using multiple email addresses to send and receive from but have been unable to get find the source of the problem.
See relevant code bellow
main.js
// Contact form
var form = $('#main-contact-form');
form.submit(function (event) {
event.preventDefault();
var form_status = $('<div class="form_status"></div>');
$.ajax({
url: $(this).attr('action'),
beforeSend: function () {
form.prepend(form_status.html('<p><i class="fa fa-spinner fa-spin"></i> Email is sending...</p>').fadeIn());
}
}).done(function (data) {
form_status.html('<p class="text-success">Thank you for contact us. As early as possible we will contact you</p>').delay(3000).fadeOut();
});
});
sendemail.php
<?php
$name = #trim(stripslashes($_POST['name']));
$from = #trim(stripslashes($_POST['email']));
$subject = #trim(stripslashes($_POST['name']));
$message = #trim(stripslashes($_POST['message']));
$to = '\\myemailaddress//';
$headers = array();
$headers[] = "MIME-Version: 1.0";
$headers[] = "Content-type: text/plain; charset=iso-8859-1";
$headers[] = "From: {$name} <{$from}>";
$headers[] = "Reply-To: <{$from}>";
$headers[] = "Subject: {$subject}";
$headers[] = "X-Mailer: PHP/".phpversion();
mail($to, $subject, $message, $headers);
die;
index.html
<div class="col-md-8 col-sm-12">
<div class="contact-form bottom">
<h2>Send a message</h2>
<form id="main-contact-form" name="contact-form" method="post" action="sendemail.php">
<div class="form-group">
<input type="text" name="name" class="form-control" required="required" placeholder="Name">
</div>
<div class="form-group">
<input type="email" name="email" class="form-control" required="required" placeholder="Email Id">
</div>
<div class="form-group">
<textarea name="message" id="message" required="required" class="form-control" rows="8" placeholder="Your text here"></textarea>
</div>
<div class="form-group">
<input type="submit" name="submit" class="btn btn-submit" value="Submit">
</div>
</form>
</div>
</div>
Thanks you in advance!

Next issue is you aren't sending any data with your ajax. Using $(formSelector).serialize() simplifies gathering the data
$.ajax({
url: $(this).attr('action'),
//serialize form data and include it with request
data: form.serialize(),
beforeSend: function () {
...
}
}).done(function (data) {
....
});
Currently if you did print_r($_POST); in your php you would see it is empty

After work from #charlietfl answer. Changing the type and url seemed to fix it.
Working code underneath :
main.js:
var form = $('#main-contact-form').serialize();
form.submit(function (event) {
event.preventDefault();
var form_status = $('<div class="form_status"></div>');
$.ajax({
url: $(this).attr('action'),
type: 'POST',
dataType: "json",
beforeSend: function () {
form.prepend(form_status.html('<p><i class="fa fa-spinner fa-spin"></i> Email is sending...</p>').fadeIn());
}
}).done(function (data) {
form_status.html('<p class="text-success">' + data.message + '</p>').delay(3000).fadeOut();
});
});
and my .php
<?php
header('Content-type: ');
$status = array(
'type'=>'success',
'message'=>'Thank you for contact us. As early as possible we will contact you '
);
$name = #trim(stripslashes($_POST['name']));
$email = #trim(stripslashes($_POST['email']));
$subject = #trim(stripslashes($_POST['subject']));
$message = #trim(stripslashes($_POST['message']));
$email_from = $email;
$email_to = '\\myemail//';
$body = 'Name: ' . $name . "\n\n" . 'Email: ' . $email . "\n\n" . 'Subject: ' . $subject . "\n\n" . 'Message: ' . $message;
$success = #mail($email_to, $subject, $body, 'From: <'.$email_from.'>');
echo json_encode($status);
die;

Related

Send Form data in Email using PHP without refreshing the page

I have a contact section in my website. I want when a user submit the form all the data should be sent in email plus the page don't reload.
My form:
<label for="name">Name:</label>
<input type="text" class="form-control" name="name" id="name" >
</div>
<div class="form-group">
<label for="email">E-Mail:</label>
<input type="email" class="form-control" name="email" id="email" >
</div>
<div class="form-group">
<label for="mobile">Mobile Number:</label>
<input type="text" class="form-control" name="mobile" id="mobile">
</div>
<div class="form-group">
<label for="message">Message:</label>
<textarea class="form-control" rows="5" name="message" id="message"></textarea>
</div>
<button type="submit" id="send" class="btn btn-primary" style="width: 100%" name="form_submit">Send Message</button>
Javascript
$(document).ready(function(){
$('#send').click(function(){
var name = $('#name').val();
var email = $('#email').val();
var mobile = $('#mobile').val();
var message = $('#message').val();
var varData = 'name=' + name + '&email=' + email + '&mobile=' + mobile + '&message=' + message;
$.ajax({
type: 'POST',
url: 'process.php',
data: varData,
success: function() {
alert("message sent");
}
});
});
});
</script>
Process.php
if (isset( $_POST['form_submit'] ) ) {
// Do processing here.
$name = $_POST['name'];
$email = $_POST['email'];
$mobile = $_POST['mobile'];
$message = $_POST['message'];
if ($name == '' || $email == '' || $mobile=='' || $message=='')
{
echo "<script> alert('please fill the field');
</script>";
exit;
}
elseif ($_POST["email"]<>'') {
$ToEmail = 'email#gmail.com';
$EmailSubject = 'Website Contact form';
$mailheader = "From: ".$_POST["email"]."\r\n";
$mailheader .= "Reply-To: ".$_POST["email"]."\r\n";
$mailheader .= "Content-type: text/html; charset=iso-8859-1\r\n";
$MESSAGE_BODY = "Name: ".$_POST["name"]."<br><br>";
$MESSAGE_BODY .= "email: ".$_POST["email"]."<br>";
$MESSAGE_BODY .= "mobile: ".nl2br($_POST["mobile"])."<br>";
$MESSAGE_BODY .= "message: ".nl2br($_POST["message"])."";
mail($ToEmail, $EmailSubject, $MESSAGE_BODY, $mailheader) or die ("Failure");
echo "<script> alert('mail sent')
</script>";
exit;
} else{
echo "<script> alert ('there is some problem');</script>";
};
}
?>
The problem is the form is not using the code mentioned in "process.php"
How can I ensure the form data is sent in email? I have searched the previous answers but couldn't fix this.

Contact form sends mail with empty message field

When i send an email with my contact form the textarea value does not send and the "message:" field is always empty in the email.
Declaring the input variables manually in jquery instead of using serialize gives the same result.
The textarea is inside the form tags so i have no idea why its value is not picked up and posted.
I've tried giving the textarea an id="message" and calling it manually in jquery like: var text = $("#message").val(); and var text = $("textarea#message").val(); but it still doesn't send.
I don't know what i'm doing wrong. Please help.
Here is my code:
<form id="contactForm" method="POST">
<div class="row small-margin">
<div class="col-md-4">
<i class="pe-7s-user pe-2x icon-contact"></i>
<input name="name" type="text" placeholder="Name(required)" required size="35">
</div>
<div class="col-md-4">
<i class="pe-7s-mail pe-2x icon-contact"></i>
<input name="email" type="email" placeholder="Email(required)" required size="35">
</div>
<div class="col-md-4">
<i class="pe-7s-link pe-2x icon-contact"></i>
<input name="website" type="text" placeholder="Website" size="35">
</div>
</div>
<div class="row small-margin">
<div class="col-md-12">
<!-- Message Field -->
<textarea name="message" placeholder="Your Message(required)" required></textarea>
<!-- Submit Button -->
<button id="submit" name="submit" type="submit" class="button" value="submit">SEND MESSAGE</button>
<!-- Success Message -->
<div id="msgSubmit" class="alert alert-success text-center hidden">Message Sent Successfully</div>
</div>
</div>
</form>
And JS:
$("#contactForm").submit(function(event){
// cancels the form submission
event.preventDefault();
console.log( $( this ).serialize() );
});
$.ajax({
type: "POST",
url: "php/form-process.php",
data: "name=" + name + "&email=" + email + "&website=" + website + "&message=" + text,
success : function(text){
if (text == "success"){
formSuccess();
}
}
});
}
function formSuccess(){
$( "#msgSubmit" ).removeClass( "hidden" );
}
And PHP:
<?php
// Set variables
$name = $_POST['name'];
$email = $_POST['email'];
$website = $_POST['website'];
$message = $_POST['text'];
$to = 'novakim92#gmail.com';
$subject = 'New Message from Nixo';
// Prepare email body text
$Body .= "Name: ";
$Body .= $name;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $email;
$Body .= "\n";
$Body .= "Website: ";
$Body .= $website;
$Body .= "\n";
$Body .= "Message: ";
$Body .= $message;
$Body .= "\n";
// Send email
$success = mail($to, $subject, $Body, "From:".$email);
if ($success){
echo "success";
}else{
echo "<p>Something went wrong, please try again!</p>";
}
?>
I found the issue on your code:
the Values from textarea never made it the Server side, because you are doing this in your PHP:
$message = $_POST['text'];
You should do this in order to get the value from textarea:
$message = $_POST['message'];
This will solve your issue :). Hope it helps.
Your variable naming is inconsistent.
In your HTML-form you're using message for the name-attribute.
But in you're AJAX-call and in the PHP $_POST-GLOBAL you are looking for a variable called text.

Email Form: $_POST is empty after form submit

I've been all over the forums. The general reason this doesn't work is that you need a NAME attribute, not an ID. I have a name attribute and I still get empty $_POST fields on submit. I'm a beginner and have been at this for 6 hours trying to figure it out. It's probablly something simple. Please help.
I got this free template off ShapeBootstrap: https://shapebootstrap.net/item/1524963-evento-free-music-event-template
My html:
<form action="sendemail.php" method="post" name="contact-form" class="contact-form" id="main-contact-form">
<div class="form-group">
<input name="name" type="text" id="name" required="required" class="form-control" placeholder="Name">
</div>
<div class="form-group">
<input type="email" name="email" id="email" class="form-control" required="required" placeholder="Email ID">
</div>
<div class="form-group">
<textarea name="message" id="message" required class="form-control" rows="10" placeholder="Enter your message"></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary pull-right">Send</button>
</div>
<div> </div>
</form>
My php:
<?php
header('Content-type: application/json');
$status = array(
'type'=>'success',
'message'=>'Thank you for contact us. As early as possible we will contact you'
);
$name = ($_POST["name"]);
$email = ($_POST['email']);
$subject = "Website Message";
$message = ($_POST['message']);
$email_from = $email;
$email_to = 'adam.wilson45#yahoo.com';//replace with your email
$body = 'Name: ' . $name . "\n\n" . 'Email: ' . $email . "\n\n" . 'Subject: ' . $subject . "\n\n" . 'Message: ' . $message;
$success = mail($email_to, $subject, $body, 'From: <'.$email_from.'>');
echo json_encode($status);
die;
JavaScript:
// Contact form validation
var form = $('.contact-form');
form.submit(function () {'use strict',
$this = $(this);
$.post($(this).attr('action'), function(data) {
$this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
},'json');
return false;
});
$( window ).resize(function() {
menuToggle();
});
$('.main-nav ul').onePageNav({
currentClass: 'active',
changeHash: false,
scrollSpeed: 900,
scrollOffset: 0,
scrollThreshold: 0.3,
filter: ':not(.no-scroll)'
});
});
Thank you so much in advanced!
You aren't passing any data in your $.post script.
Change $.post($(this).attr('action'), function(data) { to $.post($(this).attr('action'), form.serialize(), function(data) {. The form.serialize() bit passes an object of your form data to the PHP script.
See http://api.jquery.com/jquery.post/ for more info.
THANK YOU #putvande ! Your answer pointed me in the right direction! Adding the form.serialize was close. We needed to add $this. right before it. I wish I talked to you 8hrs ago.
Answer:
Change
$.post($(this).attr('action'), function(data) {
to
$.post($(this).attr('action'), $this.serialize(), function(data) {

$_POST[] not catching HTML form input

I have a strange problem, I am passing data from an email form (HTML5) to ajax/JSON and returning false so the page does not redirect to the php script after the submit button is pressed.
If I put commas seperating each data param ($email, $name, $message), only 'name' and 'email' get passed to $_POST[], leaving out the value of$message.
However if there are no commas between the params all the inputs are caught by $_POST[].
For example (with commas): (does not redirect to php script but $message value is not caught in $_POST[])
var form = $('.contact-form');
form.submit(function (evt) {
$this = $(this);
$.post('Scripts/php/sendemail.php',{
name: $('input[name=name]').val(),
email: $('input[name=email]').val(),
message: $('input[name=message]').val()
}, function(data) {
$this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
},'json');
evt.preventDefault();
return false;
});
Output:
$name=foo
$email=bar
$message=null
Page returns false
(without commas): (redirects to php script but $message value is caught in $_POST[])
var form = $('.contact-form');
form.submit(function (evt) {
$this = $(this);
$.post('Scripts/php/sendemail.php',{
name: $('input[name=name]').val()
email: $('input[name=email]').val()
message: $('input[name=message]').val()
}, function(data) {
$this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
},'json');
evt.preventDefault();
return false; (does not redirect to `php`)
});
Output:
$name=foo
$email=bar
$message=bar
HTML Form:
<form id="main-contact-form" class="contact-form" name="contact-form" method="post" action="Scripts/php/sendemail.php">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<input type="text" name="name" class="form-control" required="required" placeholder="Name">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<input type="email" name="email" class="form-control" required="required" placeholder="Email address">
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<textarea name="message" id="message" required="required" class="form-control" rows="8" placeholder="Message"></textarea>
</div>
<div class="form-group">
<button type="submit" id="submit" class="btn btn-danger btn-lg">
Send Message
</button>
</div>
</div>
</div>
</form>
JS for form:
var form = $('.contact-form');
form.submit(function (evt) {
$this = $(this);
$.post('Scripts/php/sendemail.php',
{name: $('input[name=name]').val(),
email: $('input[name=email]').val(),
message: $('input[name=message]').val()
}, function(data) {
$this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
},'json');
evt.preventDefault();
return false;
});
PHP handler:
<?php
header('Content-type: application/json');
$status = array(
'type'=>'success',
'message'=>'Email sent! Thankyou :)'
);
$name = $_POST['name'];
$email = $_POST['email'];
$subject = 'query';
$message = $_POST['message'];
$email_from = $email;
$email_to = 'keilcarpenter01#gmail.com';
$body = 'Name: ' . $name . "\n\n" . 'Email: ' . $email . "\n\n" . 'Subject: ' . $subject . "\n\n" . 'Message: ' . $message;
$success = mail($email_to, $subject, $body, 'From: visitor');
echo json_encode($status);
#start buffering (all activity to the buffer)
ob_start() ;
# dumps to buffer
var_dump($_POST) ;
# dump buffered $classvar to $outStringVar
$outStringVar = ob_get_contents() ;
# open your file with append, read, write perms
# (be sure to check your file perms)
$fp=fopen('dmp.txt','a+');
# write output to file & close it
fwrite($fp, $outStringVar );
fclose($fp);
# clean the buffer & stop buffering output
ob_end_clean() ;
die;
In this case how does the comma seperatores determine what input by form gets caught by $_POST[]?
You have to change the jquery for get value of textarea, try following code for that :-
var form = $('.contact-form');
form.submit(function (evt) {
$this = $(this);
$.post('Scripts/php/sendemail.php',
{name: $('input[name=name]').val(),
email: $('input[name=email]').val(),
message: $('textarea[name=message]').val()
}, function(data) {
$this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
},'json');
evt.preventDefault();
return false;
});
It may help you.
Use:
message: $('textarea[name=message]').val()

Fadeout Email Form

I am attempting to have a bootstrap contact form fade out on submit.
I am working with code I have found (which I've slightly modified to suit my needs), and I am having trouble with its implementation. I'm fairly new and I seem to have gotten quite stuck.
Here is the JS:
$('contactUs').on('submit', function mailMe(form) {
form.preventDefault(); //Prevents default submit
var form = $(this);
var post_url = form.attr('action');
var post_data = form.serialize(); //Serialized the form data for process.php
$('#loader', form).html('<img src="http://domain.com/test/images/loading.gif" /> Please Wait...');
$.ajax({
type: 'POST',
url: 'http://domain.com/test/process.php', // Your form script
data: post_data,
success: function(msg) {
$(form).fadeOut(500, function(){
form.html(msg).fadeIn();
});
}
});
});
Here is the Form:
<form name="contactUs" onSubmit="return mailMe(this.form)" >
<div class="inputWrap">
<div class="fname">
<input class="myInput miLeft" type="text" placeholder="Name">
</div>
<div class="femail">
<input class="myInput miRight" type="text" placeholder="Email">
</div>
</div>
<div class="taWrap">
<textarea class="myTa" type="text" placeholder="Message"></textarea>
</div>
<button class="btns btn-3 btn-3g btnsx">Send</button>
</form>
And here is the process.php:
<?php
/* Configuration */
$subject = 'New Customer Email'; // Set email subject line here
$mailto = 'myemail#me.com'; // Email address to send form submission to
/* END Configuration */
$name = $_POST['name'];
$email = $_POST['email'];
$messageContent = $_POST['messageContent'];
$timestamp = date("F jS Y, h:iA.", time());
// HTML for email to send submission details
$body = "
<br>
<p>The following information was submitted through the contact form on your website:</p>
<p><b>Name</b>: $name<br>
<b>Email</b>: $email<br>
<b>Message</b>: $messageContent<br>
<p>This form was submitted on <b>$timestamp</b></p>
";
// Success Message
$success = "
<div class=\"row-fluid\">
<div class=\"span12\">
<h3>Submission successful</h3>
<p>Thank you for taking the time to contact Shaz Construction & Design. A representative will be in contact with you shortly. If you need immediate assistance or would like to speak to someone now, please feel free to contact us directly at <strong>(415) 382-8442</strong>.</p>
</div>
</div>
";
$headers = "From: $name <$email> \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";
$message = "<html><body>$body</body></html>";
if (mail($mailto, $subject, $message, $headers)) {
echo "$success"; // success
} else {
echo 'Form submission failed. Please try again...'; // failure
}
?>
There are a few small things you are missing:
Your jQuery selector for the form is incorrect - give your form an ID attribute of contactUs, and then use the selector $('form#contactUs'). Get rid of the name attribute on the form.
Your button element needs to be of type submit - your button currently does nothing.
You don't need the onSubmit attribute, you are already binding your form to an event in the JS.
Your input tags currently do not have any name elements on them - they are required - see http://api.jquery.com/serialize/
You try to access an attribute on the form that does not exist (action), but you don't use it, so just remove that line.
Use return false rather than preventDefault in your event handler (I couldn't get preventDefault to work. That might just be me though!)
I can't tell this because of the context of your code, but ensure that your JS is within a $('document').ready(function() { ... } block.
I think that your JS and HTML should be:
JS
$('form#contactUs').on('submit', function() {
var form = $(this);
var post_data = form.serialize(); //Serialized the form data for process.php
$('#loader').html('<img src="http://yasharsahaleh.com/test/images/loading.gif" /> Please Wait...');
$.ajax({
type: 'POST',
url: 'http://yasharsahaleh.com/test/process.php', // Your form script
data: post_data,
success: function(msg) {
$('#loader').html('');
// We know this is the form that needs fading in/out
$('form#contactUs').fadeOut(500, function(){
$('form#contactUs').html(msg).fadeIn();
});
}
});
return false;
});
HTML
<form id="contactUs">
<div class="inputWrap">
<div class="fname">
<input name="name" class="myInput miLeft" type="text" placeholder="Name">
</div>
<div class="femail">
<input name="email" class="myInput miRight" type="text" placeholder="Email">
</div>
</div>
<div class="taWrap">
<textarea name="messageContent" class="myTa" type="text" placeholder="Message"></textarea>
</div>
<button type="submit" class="btns btn-3 btn-3g btnsx">Send</button>
</form>
I made a small JSFiddle to illustrate most of this (taking out the AJAX part): http://jsfiddle.net/dualspiral/2rXas/1/
The PHP needs changing slightly, you are not actually printing out the variable contents. The body variable shoud actually be assigned:
$body = "
<br>
<p>The following information was submitted through the contact form on your website:</p>
<p><b>Name</b>: " . $name . "<br>
<b>Email</b>: " . $email . "<br>
<b>Message</b>: " . $messageContent . "<br>
<p>This form was submitted on <b>" . $timestamp . "</b></p>
";
and the last lines should read:
$headers = "From: " . $name . " <" . $email . "> \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";
$message = "<html><body>" . $body . "</body></html>";
if (mail($mailto, $subject, $message, $headers)) {
echo $success; // success
} else {
echo 'Form submission failed. Please try again...'; // failure
}
?>

Categories