Jquery empty results - javascript

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);
?>

Related

"Undefined" response when submitting contact form without page refresh

I am building a basic contact form (three fields) for my site. I have the form built in HTML and CSS; all I had to do was build the PHP to make the form responses send to my email. I found a tutorial and built the PHP file (which worked), but wanted the form to submit in the background and not leave the original page. I found an online tutorial to do that using Ajax, and after some tweaking, I got it mostly to work. The only issue I'm having now is that when I receive the email with the response, the message field is coming back as "undefined."
I have a good grasp on HTML and CSS, but PHP and JS are new to me (just started learning them for this project), so any help on how to fix this issue and possibly correct any wrong code would be a huge help. I've included the form HTML, PHP, and JS below (PHP and JS are both named 'contact.[filetype]'.
HTML
<div id="contact_form">
<form name="contact" action="">
<div class="field">
<label for="name">Name</label>
<input type="text" name="name" id="name" required/>
</div>
<div class="field">
<label for="email">Email</label>
<input type="text" name="email" id="email" required/>
</div>
<div class="field">
<label for="comments">Comments</label>
<textarea name="comments" id="comments" rows="3"></textarea>
</div>
<ul class="actions">
<li><input type="submit" name="submit" class="button" id="submit_btn" value="Send Message" /></li>
</ul>
</form>
</div>
PHP
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$comments = $_POST['comments'];
$formcontent="From: $name \n Message: $comments \n";
$recipient = "alltheladsmedia#gmail.com";
$subject = "Message From Website";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo "Thank You!" . " -" . "<a href='index.html' target='_blank' style='text-decoration:none;color:#505050;'> Return Home</a>";
?>
JS
$(function() {
$('.error').hide();
$(".button").click(function() {
// validate and process form here
$('.error').hide();
var name = $("input#name").val();
if (name === "") {
$("label#name_error").show();
$("input#name").focus();
return false;
}
var email = $("input#email").val();
if (email === "") {
$("label#email_error").show();
$("input#email").focus();
return false;
}
var message = $("input#message").val();
if (message === "") {
$("label#message_error").show();
$("input#message").focus();
return false;
}
$.ajax({
type: "POST",
url: "contact.php",
data: {name:name,email:email,message:message},
success: function() {
$('#contact_form').html("<div id='success'></div>");
$('#success').html("<h2>Your message was successfully submitted!</h2>")
.append("<p>We will get back to you within 24-48 hours.</p>")
.hide()
.fadeIn(1500, function() {
$('#success');
});
}
});
return false;
});
});
In your markup the field's id is "comments" but you are looking for "message" in your JS and PHP.
you have print your mail result
if(#mail($recipient, $subject, $formcontent, $mailheader))
{
echo "Mail Sent Successfully";
}else{
echo "Mail Not Sent";
}
Make few changes if you are using jquery 3.
Change this
$(".button").on("click", function() {
// Validation here
// Put ajax outside this block
});
Edit html form like this code.
Check the dev. tools if the action attribute is added correctly by the php.
<form id="contact" name="contact" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post" >
And ajax call into this
$("#contact").on("submit", function(e) {
e.preventDefault(); // Now the page won't redirect
var url = $(this).attr("action");
// Check console if contact is printed after the form is submitted
// If contact is printed the url is right
console.log(url);
$.ajax({
type: "POST",
url: url,
data: $(this).serialiseArray(), // Found a typo here fixed
success: function() {
// Your stuffs
}
});
});
Don't put the ajax call inside the input field verification.
Let me know if you find any issue so I can fix my code.

On form submission hide the form diva and send an email using jQuery

My objective is to send the form data as an email using php and the form div should get replaced by another div. I have done hiding the div part using jquery but not able to send and email. I have also written the code to send email but my issue is how to call the file which has email sending code.
My form code:
<form method="post" id="formsub">
<div id="form">
<div class="form-group">
<input type="text" name="name" class="form-control" id="name" placeholder="Name" required>
</div>
<div class="form-group">
<input type="text" name="email" class="form-control" id="email" placeholder="Email" required>
</div>
<div class="form-group">
<input type="text" name="phone" class="form-control" id="phone" placeholder="Phone Number" required>
</div>
<div class="form-group">
<input type="button" id="addbut" name="submit" value="Submit" class="form-control">
</div>
</div>
</form>
My code to hide the div and tried form submission script:
<script>
$(document).ready(function() {
$("#addbut").on('click', function() {
$.ajax({
type: "POST",
url: "fromemail.php",
data: $(form).serialize(),
success: function(){
$("#form").hide();
$("#address").show();
}
});
});
});
</script>
My php email sending code:
<?php
if($_POST['submit']){
$to = "akhil#redd.xyz"; // this is your Email address
$from = $_POST['email']; // this is the sender's Email address
$name = $_POST['name'];
$phone = $_POST['phone'];
$subject = "Spots Contact";
$message = $first_name . ", with " . $phone . "has enquired for the service";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
if(mail($to,$subject,$message,$headers))
{
echo "<script>alert('We will contact you shortly');</script>";
}
}
?>
Give file name in form action attribute :
<form id="formsub" method="post" action="fromemail.php">
and do ajax code like this :
$(document).ready(function(){
var form=$("#formsub");
$("#addbut").click(function(){
$.ajax({
type:"POST",
url:form.attr("action"),
data:$("#formsub").serialize(),
success: function(response){
console.log(response);
}
});
});
});
#Rakhi..
Is this correct??
<script type="text/javascript" src="assets/js/jquery-2.2.1.min.js"></script>
<script>
$(document).ready(function() {
var form=$("#formsub");
var base_url = "www.3ding.in/spots/";
$("#addbut").on('click', function() {
$("#form").hide();
$("#address").show();
$.ajax({
type: "POST",
url: base_url + "fromemail.php",
data: $("#formsub").serialize(),
success: function(response){
alert(1);
console.log(response);
}
});
});
});

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

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