PHP mail function + ajax = frustrated me - php

I'm using ajax to submit a contact from without reloading the page, it works well for the most part except when I try to send the body of the message nothing gets sent. The to and subject parts work fine, it is just when the body tries to get sent I see nothing. I've tested it running strickly a php function and the body works, just the page reloads and I'm not sure why it works here, but not with ajax. If anybody could shed some light it'd be great, thanks.
.js
$(document).ready(function () {
$('#submit').click(function () {
var contactformdata = {
you: $('#you').val(),
subject: $('#subject').val(),
message: $('#contactbody').val(),
}
$.ajax({
url: "http://www.trenthauck.com/index.php/home/sendemail",
type: 'POST',
data: contactformdata,
success: function () {
$('#contactheader').replaceWith("<p class='header'>Thanks</p>");
$('#contactform').remove();
$('#contactlink').remove();
$(document).scrollTop(25);
}
});
return false;
});
});
Here is the php function (using CI, btw)
function sendemail(){
$to = "auck#gmail.com";
$from = $this->input->post('you');
$subject = $this->input->post('subject');
$message = $this->input->post('contactbody');
$tosend = "From: " . $from . "\nMessage: " . $message;
mail($to, $subject, $message);
$this->index();
}
And the form if that helps
<div class="divider" id="contact">
<p class = "header"><a id="contactheader" name="gocontact">Contact</a></p>
<div id = "contactform">
<form method = "post" id="contactform" action="<?php site_url()?>index.php/home/sendemail">
<div id ="formtitles">
<p class = "info">You:</p>
<p class = "info">Me:</p>
<p class = "info">Subject:</p>
<p class = "info">Body:</p>
<input id = "submit" type="submit" value="Send" />
</div>
<div id ="formfields">
<input id="you" type="text" name="you" /><br/>
<p class = "info">auck#gmail.com</p>
<input id ="subject" type="text" name="subject" /><br/>
<textarea id = "contactbody" name="contactbody"></textarea>
</div>
</form>
</div>
</div>
Thanks for the help

in the jquery you're sending the message using the variable 'message' but in the php you're picking it up using 'contactbody'.
change the php from:
$message = $this->input->post('contactbody');
to:
$message = $this->input->post('message');

Related

Wordpress and Ajax form submission

I'm totally lost here. Can anyone check what is going wrong with the form I'm trying to create here? It should send data with Ajax in WP custom theme without storying anything in the DB.
The console gives me an error that "firstname is not defined", line 67 of jQuery - data:{name:firstname, email:email, message:comment,action:'validate_form'} , but truly, I believe it will be more than that.
<form class="form">
<div class="form__item form__item_no-margin">
<input type="text" name="firstname" placeholder="What's your name?*" class="firstname" required>
<p class="error-message">This is field is required!</p>
</div>
<div class="form__item">
<input type="text" name="email" placeholder="What's your email address?*" class="email" required>
<p class="error-message">This is field is required!</p>
</div>
<div class="form__item">
<textarea name="comment" placeholder="Please, leave a message!*" class="textarea" required></textarea>
<p class="error-message">This is field is required!</p>
</div>
<div class="form__item">
<input type="button" name="submit" value="Send" class="submit-btn">
<p class="error-message error-message_main val-error">All the required fields have to be filled out.</p>
<p class="success-message val-success">Thanks. I'll contact you ASAP!</p>
</div>
</form>
And some jQuery:
jQuery(document).ready(function(){
jQuery(".submit-btn").click(function(e){
e.preventDefault();
var name = jQuery(".firstname").val();
var email = jQuery(".email").val();
var message = jQuery(".textarea").val();
var ajaxUrl = "/wp-admin/admin-ajax.php";
if(name === "" || email === "" || message === "") {
jQuery(".val-error, .error-message").show();
jQuery("html, body").animate({
scrollTop: jQuery(".val-error").offset().top
}, 700)
}
else {
jQuery.ajax({
url: ajaxUrl,
method:"POST",
data:{name:firstname, email:email, message:comment,action:'validate_form'},
success: function(data) {
jQuery("form").trigger("reset");
jQuery(".val-success").show(fast);
}
});
}
});
});
PHP in the functions.php file:
add_action('wp_ajax_myaction', 'my_action_callback');
add_action('wp_ajax_nopriv_myaction', 'my_action_callback');
function my_action_callback(){
$name= trim($_POST["firstname"]);
$email = trim($_POST["email"]);
$comment = trim($_POST["comment"]);
$page_title = "New form submission";
$message = "Name: $name \nEmail: $email \nMessage: $comment";
mail('some#email.com', $page_title, $message, "Content-type: text/plain; charset=\"utf-8\"\n From: some#email.com" );
wp_die();
}
UPDATE
Attached is the fresh version in codepen. PHP is down below.
https://codepen.io/anon/pen/RVWaJY
add_action('wp_ajax_myaction', 'validate_form_callback');
add_action('wp_ajax_nopriv_myaction', 'validate_form_callback');
function validate_form_callback(){
$name= trim($_POST["firstname"]);
$email = trim($_POST["email"]);
$comment = trim($_POST["comment"]);
$page_title = "New form submission";
$message = "Name: $name \nEmail: $email \nMessage: $comment";
mail('some#email.com', $page_title, $message, "Content-type:
text/plain; charset=\"utf-8\"\n From: some#email.com" );
wp_die();
}
Think it may just be this typo:
var name = jQuery(".firstname").val();
The variable passed to data
name:firstname,
Let me know if that solves your problem. If not, I will look again. : )
The first issue with the code you've posted, as you've already identified, is the error in the console.
You're creating a variable name (ln 4) and then trying to reference it as firstname (ln 19). You're doing the same thing in the PHP callback. The object in the AJAX request sets the value as name yet you're trying to retrieve it with firstname.
The same problem applies to comment. The best approach would be to pick a label and use it consistently. Mixing comment and message will only lead to confusion.
The second issue is with the action. Your JS code sets the action as validate_form but your callback fires on myaction.
JS Updates:
. . .
var firstname = jQuery( ".firstname" ).val();
var email = jQuery(".email").val();
var comment = jQuery(".textarea").val();
. . .
method:"POST",
data: {
firstname: firstname,
email: email,
comment: comment,
action: 'validate_form'
},
PHP Updates:
add_action( 'wp_ajax_validate_form', 'validate_form_callback' );
add_action( 'wp_ajax_nopriv_validate_form', 'validate_form_callback' );
function validate_form_callback() {
Hello your data parameter need to be instead like this, you have inverted the way is suppose to be writting, your variable should be on the right side and the name you are going to use to call it in the php code should be in the left side:
data:{firstname:name, email:email, comment:message, action:'validate_form'},
remember that your variable your are passing are:
var name = jQuery(".firstname").val(); var email = jQuery(".email").val(); var message = jQuery(".textarea").val();
and in your php you are going to call like this:
$name= trim($_POST["firstname"]); $email = trim($_POST["email"]); $comment = trim($_POST["comment"]);

$POST is returning empty values from HTML form

I am newbie for HTML and PHP programming.
When i am submitting data from form $POST is not fetching values from form and simply empty values are getting mailed .spent quite a lot time for this but couldn't figured it out..
following is part of a code of my HTML Form
<form id="main-contact-form" class="contact-form" name="contact-form" method="POST" action="sendemail.php">
<div class="form-group">
<input type="text" name="namefirst" class="form-control" required="required" placeholder="Name">
</div>
<div class="form-group">
<input type="email" name="emailfirst" class="form-control" placeholder="Email ID">
</div>
<div class="form-group">
<input type="tel" name="tel" class="form-control" placeholder="Mobile No">
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary pull-right">Send</button>
</div>
</form>
following is my PHP code
<?php
header('Content-type: application/json');
$status = array(
'type'=>'success',
'message'=>'Thank you for registering wth us.We will keep updating you.'
);
{
$name = $_POST["namefirst"];
$email = #trim(stripslashes($_POST["emailfirst"]));
$email_from = $email;
$email_to = '****';//replace with your email
$body = 'Name: ' . $name . "\n\n" . 'Email: ' . $email . "\n\n" ;
$success = #mail($email_to, $subject, $body, 'From: <'.$email_from.'>');
echo json_encode($status);
}
?>
i have tried all the possible solutions,but its just not working.Please let me know what is wrong with this.
i figured it out ..problem is not with PHP or HTML file it is with javascript code,values were not getting set there #MueyiwaMosesIkomi thanks alot becoz of this i got this problem so to solve this I did following thing:
EARLIER my code was:
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;
});
which was not sending values. after this code its working;
var form = $('.contact-form');
var namefirst= $('.contact-form' . 'namefirst').val();
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;
});
now its sending values but it is going on next page and showing php echo as it is,not encoding Json so i thnik
$this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
},'json');
this part of code is not working...can anyone help regarding this??????
Thanks all of you

Ajax not capturing php contact form script

I have a contact form on my website that is not posting the success or error message as it should.
The weird thing is I have used this exact same form, php, and ajax script on several other sites and it works great. In fact, it used to work great on the site in question.
The website is https://www.pouncingfoxdesign.com. The contact form is at the bottom. Feel free to fill it out for testing purposes.
Here's the form and script:
<div class="col-md-8 col-sm-9 wow form1 fadeInLeft">
<div class="contact-form clearfix contactForm">
<form id="form" action="php/email.php" class="contactForm"
method="post">
<div class="messages"></div>
<div class="input-field">
<input type="text" class="form-control" name="name"
placeholder="Your Name" required="">
</div>
<div class="input-field">
<input type="email" class="form-control"
name="email" placeholder="Your Email" required="">
</div>
<div class="input-field message">
<textarea name="message" class="form-control"
placeholder="Your Message" required=""></textarea>
</div>
<input type="submit" name="submit" class="btn btn-blue
pull-right" value="SEND MESSAGE" id="msg-submit">
<div class="g-recaptcha fadeInLeft" data-
sitekey=""></div>
</form>
</div> <!-- end .contact-form -->
</div> <!-- .col-md-8 -->
<script> $('#form').on('submit', function(e) {
event.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="img/forms/loading.gif" />
Please Wait...');
$.ajax({
type: 'POST',
url: 'php/email.php', // Your form script
data: post_data,
success: function(msg) {
var old_html = form.html()
$(form)
.html(msg).fadeIn();
setTimeout(function(){
$(form)
.html(old_html).fadeIn();
}, 4000);
},
error: function(xhr, ajaxOptions, err){
var old_html = form.html()
$(form).fadeOut(500)
.html("<h3>There was an error. Please try again.
</h3>").fadeIn();
setTimeout(function(){
$(form).fadeOut(500)
.html(old_html).fadeIn();
}, 3000);
}
});
});
</script>
And here's the PHP:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$success = "
<div class=\"row-fluid\">
<div class=\"span12\">
<h1>Submission successful</h1>
<h3>Thank you for contacting us!</h3>
</div>
</div>";
$to = "email#email.com";
$subject = "$name\n filled Pouncing Fox Desing Form";
$txt = "From: $name\n E-Mail: $email\n Comments:\n $message";
$headers = "From: Pouncing Fox Design" . "\r\n" ;
if(isset($_POST['g-recaptcha-response'])){
$captcha=$_POST['g-recaptcha-response'];
}
if(!$captcha){
echo '<h2>Please check the the captcha form.</h2>';
exit;
}
$secretKey = "";
$ip = $_SERVER['REMOTE_ADDR'];
$response=file_get_contents
("https://www.google.com/recaptcha/api/siteverify?
secret=".$secretKey."&response=".$captcha."&remoteip=".$ip);
$responseKeys = json_decode($response,true);
if (mail($to, $subject, $txt, $headers)) {
echo "$success"
} else {
echo 'Form submission failed. Please try again...'; // failure
}
?>
What I want it to do is replace the form with the success message for a few seconds and then go back to the form. What it does instead is just go to the email.php file with the success message being all that's on the screen.
If you want to check out https://www.mooreengaging.com, the same script and php file is used for that site. It works great and you can see my intended results. Again, feel free to fill out the form for testing purposes.
I have tried to use other ajax scripts and have tried to rework it several different times, but no matter what when clicking submit it just loads the php file. It's like it is bypassing the ajax script altogether.
Thanks!
EDIT:
I have received the emails from you guys testing and they look right. So it is working, just not posting the success message as I'd like.
Ok, I figured it out. I added <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> to the top of the page under the header.
I thought it was best to put jquery at the bottom?
Did it fail because I was trying to run that script before it loaded jquery?
Change
$('#form').on('submit', function(e)
To
$('#form').on('submit', function(event)
Because you use
event.preventDefault();

Form sending email but in the email $_POST values are blank

I have read many forums where this exact question posted but there is no satisfactory answer. Some posts seem to have found out how to make it work but the answer is not shared or only partly answered.
the answer that i see the most is (but don't know how to use it):
var form = $('.contact-form');
form.submit(function () {'use strict',
$this = $(this);
$.post("sendemail.php", $(".contact-form").serialize(),function(result){
if(result.type == 'success'){
$this.prev().text(result.message).fadeIn().delay(3000).fadeOut();
}
});
return false;
});
the problem with this is that $_POST is not being sent. The mail function is working but the mail contents are blank
my mail message:
Name:
Email:
Subject:
Message:
exactly this is in my mail when I fill the form with data and nothing is being sent
main.html
<h4>Contact Form</h4>
<div class="status alert alert-success" style="display: none"></div>
<form id="main-contact-form" class="contact-form" name="contact-form" method="post" action="sendemail.php" role="form">
<div class="row">
<div class="col-sm-5">
<div class="form-group">
<input type="text" class="form-control" name="subject" required="required" placeholder="Subject">
</div>
<div class="form-group">
<input type="text" class="form-control" name="name" required placeholder="First Name">
</div>
<div class="form-group">
<input type="text" class="form-control" name="email" required placeholder="Email address">
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-lg">Send Message</button>
</div>
</div>
<div class="col-sm-7">
<textarea name="message" id="message" required class="form-control" rows="8" placeholder="Message"></textarea>
</div>
</div>
</form>
sendemail.php
<?php
header('Content-type: application/json');
$status = array(
'type'=>'success',
'message'=>'Email sent!'
);
$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#gmail.com';
$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;
Is your form possibly getting submitted twice? (once completed and then blank) The html form is already fully wired to POST without the use of the submit handler, which is redundant.
If I'm going to submit a form via AJAX, I typically set only the id of the form (i.e. no action and no method attributes) and I use a regular button (not submit) as the submit button. This makes it clear that jQuery will be handling the POSTing.
<form id="main-contact-form" class="contact-form" role="form">
...fields
<button id="btn_submit" class="btn btn-primary">Submit</button>
</form>
Then in jQuery
'use strict';
var form = $('.contact-form'),
btn_submit = $('#btn_submit');
btn_submit.on('click', function(e) {
e.preventDefault(); //prevent default button behavior
$.post('sendemail.php', form.serialize(),function(result){
if(result.type == 'success'){
form.prev().text(result.message).fadeIn().delay(3000).fadeOut();
}
});
Change your "jquery" code as shown below:
$('.contact-form').submit(function (e) {
e.preventDefault(); // prevent default form 'submit' event
$this = $(this);
$.post(
"sendemail.php",
$(".contact-form").serialize(),
function(result){
if(result.type == 'success'){
$this.prev().text(result.message).fadeIn().delay(3000).fadeOut();
}
},
'json' // expecting a JSON response from server
);
});
I think you have multiple forms with the css class .contact-form in the same page. If you want to submit this form, then you can use form id selector.
<script type="text/javascript">
$(function() {
$('#main-contact-form').submit(function (e) {
e.preventDefault(); // prevent default form 'submit' event
var $this = $(this);
$.post("sendemail.php", $this.serialize(), function(result) {
if (result.type == 'success') {
$this.prev().text(result.message)
.fadeIn().delay(3000).fadeOut();
}
}
}, 'json');
});
</script>
Or you can write the code using the css selector as follows:
<script type="text/javascript">
$(function() {
$('.contact-form').submit(function (e) {
e.preventDefault(); // prevent default form 'submit' event
var $this = $(this);
$.post("sendemail.php", $this.serialize(), function(result) {
if (result.type == 'success') {
$this.prev().text(result.message)
.fadeIn().delay(3000).fadeOut();
}
}
}, 'json');
});
</script>

404 error ajax, code works with straight php / html

so my code works fine by itself, but I'm trying to add some ajax into it. I'm using CI, to do some of the lifting. I don't understand why it's giving a 404 if the code works fine without ajax.
Here is the form:
<div class="divider" id="contact">
<p class = "header"><a id="contactheader" name="gocontact">Contact</a></p>
<div id = "contactform">
<form method = "post" id="contactform" action="<?php site_url()?>index.php/home/sendemail">
<div id ="formtitles">
<p class = "info">You:</p>
<p class = "info">Me:</p>
<p class = "info">Subject:</p>
<p class = "info">Body:</p>
<input id = "submit" type="submit" value="Send" />
</div>
<div id ="formfields">
<input id="you" type="text" name="you" /><br/>
<p class = "info">#gmail.com</p>
<input id ="subject" type="text" name="subject" /><br/>
<textarea id = "contactbody"></textarea>
</div>
</form>
</div>
</div>
The .js
$(document).ready(function() {
$('#submit').click(function(){
var contactformdata = {
you: $('#you').val(),
subject: $('#subject').val(),
message: $('#message').val(),
}
console.log(you);
$.ajax({
url: "trenthauck.com/index.php/home/sendemail",
type: 'POST',
data: contactformdata,
success: function(){
$('#contactheader').replaceWith("<p class='header'>Thanks</p>");
$('#contactform').remove();
$('#contactlink').remove();
$(document).scrollTop(25);
}
});
return false;
});
});
And finally the controller:
<!--
Name: Trent Hauck
Date: INSERT
File: INSERT
Desc: INSERT
-->
<?php
class Home extends Controller{
function index(){
$this->load->view('home_view');
return true;
}
function sendemail(){
$to = "trent.hauck#gmail.com";
$from = $this->input->post('you');
$subject = $this->input->post('subject');
$message = $this->input->post('contactbody');
$message = wordwrap($message, 75);
$tosend = "From: " . $from . "\nMessage: " . $message;
mail($to, $subject, $tosend);
$this->index();
}
}
Side question, assuming you're still reading. Is there anyway to do something like site_url() from CI in the .js so I don't have to call the whole thing. Thanks
You forgot http:// at the beginning of your Ajax url parameter:
So the browser thinks you're pointing it to [site_url]/trenthauck.com/index.php/home/sendemail, which, in all likelihood, isn't what you intended.

Categories