Email Form: $_POST is empty after form submit - javascript

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) {

Related

Contact form doesn't send textarea value [duplicate]

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.

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.

Jquery empty results

Problem
I tried after submitting the form not redirect to email php. For that I used ajax and its somehow working however it's gives back empty result. I have problem with javascript but thats enough difficult to find for my beginner level. I tested to send email without ajax and it sending normally. But redirecting to empty page email.php
HTML
<form method="POST" id="myForm" data-toggle="validator" action="email.php">
<h2 class="section-heading">Свяжитесь с нами:</h2>
<div class="form-group">
<label for="exampleInputEmail1">Имя:</label>
<input style="background:none;" id="firstName" name="firtname" class="form-control" placeholder="Имя" required>
<p id="p1"></p>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Тема:</label>
<input style="background:none;" id="subjectTheme" name="subject" class="form-control" placeholder="Тема" required>
<p id="p2"></p>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Электронная почта:</label>
<input style="background:none;" type="email" id="email" name="email" class="form-control" placeholder="Электронная почта" required>
<p class="help-block with-errors"></p>
</div>
<div class="form-group">
<label>Сообщение:</label>
<textarea style="background:none;" name="message" class="form-control" rows="3"></textarea>
</div>
<input type="submit" id="sendButton" class="btn btn-default"/>
</form>
Javascript
$('#myForm').submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'email.php'
});
$('#myForm')[0].reset();
alert("Success!");
})
PHP
<?php
$to = 'test#mail.ru'; // Replace with your email
$subject = $_POST['subject']; // Replace with your $subject
$headers = 'From: ' . $_POST['email'];
$message = 'Имя: ' . $_POST['firtname'] . "\n" .
'Электронная почта: ' . $_POST['email'] . "\n" .
'Тема: ' . $_POST['subject'] . "\n" .
'Сообщение: ' . $_POST['message'];
mail($to, $subject, $message, $headers);
?>
You need to pass the informations through AJAX. And reset your form on AJAX success. You didn't do that now.
Should look like this:
$('#myForm').submit(function(e) {
e.preventDefault();
var firstname = $('#firstName').val();
var subject = $('#subjectTheme').val();
var email = $('#email').val();
var message = $('#message').val();
$.ajax({
type: 'POST',
url: 'email.php',
data: {firstname: firstname, subject: subject, email: email, message: message },
success: function(){
$('#myForm')[0].reset();
alert("Success!");
}
});
})
You need to pass the content of the form and move the alert and reset to the callback:
$('#myForm').on("submit",function(e) {
e.preventDefault();
$.post(
$(this).attr("action"),
$(this).serialize(),
function(response) {
alert("success");
$('#myForm')[0].reset();
}
);
});
Your email.php file should send a status message to your ajax based on mail is sent or not. You should send your form data to email.php file.
your script
$('#myForm').on("submit",function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'email.php',
data: $('#myForm').serialize(),
success: function(data) {
if(data == 'success') {
alert('mail sent success');
$('#myForm')[0].reset();
} else {
alert('failed');
}
}
});
your PHP
<?php
...
...
if(mail($to, $subject, $message, $headers)) {
$status = 'success';
} else {
$status = 'failed';
}
die($status);
?>

Website contact form not receiving messages

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;

$_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()

Categories