Sending email in WordPress using jQuery and ajax - php

I have a little problem here. I'm working on a simple quotation form on wordpress.
I have two forms, the first one sends data to jQuery that does all the calcs (very few options so we didn't use a DB), then prints an html row. No issue until here; the problems start when I'm trying to send that row/rows to PHP to send a simple email. I've tried with ajax and wp_mail but with no success.
Here is what i've tried:
HTML inside wordpress template file:
<!--first form with data to calculate-->
<form class="needs-validation">
<!--select fields, no problem here-->
</form>
<div class="table-responsive"> <!--risultato preventivo-->
<table class="table table-bordered" id="dynamic_field">
<tr>
<!--result given by jQuery-->
</tr>
</table>
<p id="total"><!--total price passed by jQuery--></p>
</div>
<!--second form for sending email-->
<form action="#" method="POST">
Nome:<br>
<input type="text" name="nome" id="nome">
<br>
Cognome:<br>
<input type="text" name="cognome" id="cognome">
<br>
Email:<br>
<input type="email" name="email" id="email">
<input type="hidden" name="invia" value="s">
<input type="submit" id="inviaForm" value="Invia">
</form>
<div id="worked"></div>
jQuery with calcs inside file main.js:
(function ($) {
$(document).ready(function () {
function generaRisultato (riga,nProfilo,nColore,nSerramento,costoRiga){
var risultato = '<tr id="row' + riga +
'" class="dynamic-added"><td><div><h5 class="my-0">Articolo: ' + nProfilo +
'</h5><br><small class="text-muted">Colorazione: ' + nColore +
'</small><br><small class="text-muted">Serramento: ' + nSerramento +
'</small></div><span id="costo-riga'+riga+'">'+costoRiga+'€</span></td>'+
'<td><button type="button" name="remove" id="'+ riga +'" class="btn btn_remove">-</button>
</td></tr>';
return risultato;
}
//calcs done correctly
$('#dynamic_field').append(generaRisultato(i,profile,color,name,price)); //result printed
var risultatoFinale = $('#dynamic_field').html(); //variable with result stored for email
//sending form mail ajax
$('#inviaForm').on('submit', function(e){
//evito l'invio del form
e.preventDefault();
//recupero i valori
var nomeUser = $('#nome').val();
var cognomeUser = $('#cognome').val();
var emailUser = $('#email').val();
var totaleFinale = $('#totale').html();
var preventivoFinale = $('#dynamic_field').html();
//eseguo la chiamata ajax
$.ajax({
type: "POST",
url: my_vars.ajaxurl,
data: {
action : 'invio_mail', //azione da eseguire
_nonce : my_vars.nonce,
nome : nomeUser,
cognome : cognomeUser,
email : emailUser,
totale : totaleFinale,
preventivo : preventivoFinale
},
success: function(res){
$('#funzionante').html(res);
}
});
});
});
})(jQuery);
PHP inside functions.php:
function vf_load_theme_preventivatore(){
wp_register_script('main', get_template_directory_uri().'/preventivatore/js/main.js', false, false,
true);
wp_enqueue_script('main');
wp_localize_script( 'main', 'my_vars', array(
'ajaxurl' =>admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('invio-mail-nonce')
));
}
add_action('wp_enqueue_scripts', 'vf_load_theme_preventivatore');
function invio_mail_ajax(){
//verifico che il nonce sia corretto
if(!wp_verify_nonce( $_REQUEST['_nonce'], 'invio-mail-nonce') ){
die('Non autorizzato!');
}
//Prepariamo le variabili da usare
$successo = '';
$nome = strval($_REQUEST['nome']);
$cognome = strval($_REQUEST['cognome']);
$email = $_REQUEST['email'];
$preventivo = $_REQUEST['preventivo'];
$totale = $_REQUEST['totale'];
//script mail
$header = "From: Site <test#site-domain.it>\n";
$header .= "BCC: Altro Ricevente <test2#my-domain.it>\n";
// costruiamo le intestazioni specifiche per il formato HTML
$header .= "Content-Type: text/html; charset=\"UTF-8\"\n";
$oggetto = "Ecco il tuo preventivo";
$messaggio = "<html><body><p>Richiesta preventivo da sito</p><p>Nome: ".$nome."</p><p>Cognome:
".$cognome."</p><p>Email: ".$email."</p> <p>Dati del preventivo</p><p>".$preventivo."</p><p>Totale:
".$totale."€</p></body></html>";
$inviata = wp_mail($email,$oggetto,$messaggio,$header);
$successo .= '<p>'.$nome.'</p>';
echo $successo;
die();
if($inviata){
$successo = '<p> email invata</p>';
echo $successo;
die();
} else die('errore nella mail');
}
add_action('wp_ajax_invio_mail','invio_mail_ajax');
add_action('wp_ajax_nopriv_invio_mail','invio_mail_ajax');
That's what i've done, i've simply hidden the jQuery calculations because that worked flawlessly.
I wanted to send an email with an html formatted text, with this solution the email doesn't even get sent (before putting ajax and php script in fuction the email arrives, php was inside the template file), also i cannot pass the html table rows with results and the total of the quotation. Maybe i got wrong the ajax or php part.
Is there any help about this? thank you for all your support!

Created AJAX submit form. Tested working good you can change your data. Hope this help you.
Copy and paste in your function.php file
function invio_mail(){
$to = 'sendto#example.com';
$subject = 'The subject';
$body = 'The email body content';
$headers = array('Content-Type: text/html; charset=UTF-8');
wp_mail( $to, $subject, $body, $headers );
echo 'mail send';
die;
}
add_action("wp_ajax_invio_mail", "invio_mail");
add_action("wp_ajax_nopriv_invio_mail", "invio_mail");
Just paste you want the page (Form)
<form id="ajaxformid" action="#" method="POST">
Nome:<br>
<input type="text" name="nome" id="nome">
<br>
Cognome:<br>
<input type="text" name="cognome" id="cognome">
<br>
Email:<br>
<input type="email" name="email" id="email">
<input type="hidden" name="invia" value="s">
<input type="submit" id="inviaForm" value="Invia">
</form>
Just paste in footer
<script>
jQuery(document).ready(function($) {
var frm = $('#ajaxformid');
frm.submit(function (e) {
var formData = {
nome: jQuery('#nome').val(),
cognome: jQuery('#cognome').val(),
email: jQuery('#email').val(),
action:'invio_mail'
};
$.ajax({
type : 'POST',
url : "<?php echo admin_url('admin-ajax.php'); ?>",
data : formData,
dataType : 'json',
encode : true
}).done(function(data) {
console.log(data);
}).fail(function(data) {
console.log(data);
});
e.preventDefault();
});
});
</script>

Related

Sumbit form with two buttons and ajax

I have a form made with ajax, in this form there are 2 submits, both have the same function as sending an email but depending on whether the user uses one or the other the email must indicate this selection.
I tried to use the isset function to see which of the two buttons to submit but when I receive this parameter it is empty.
HTML form
<form id="form-landing" data-ajax="<?php echo admin_url('admin-ajax.php?action=contactlanding'); ?>">
<?php while (have_posts()) : the_post();
the_content();
endwhile; ?>
<?php wp_nonce_field(); ?>
<div id="step1">
<div class="group-form">
<p>1.- question 1</p>
<div>
<label for="afrontarsi">Yes</label><input type="radio" name="afrontar" value="Si" id="afrontarsi">
<label for="afrontarno">No</label><input type="radio" name="afrontar" value="No" id="afrontarno">
</div>
</div>
<div class="group-form">
<p>2. - Question 2</p>
<div>
<input type="text" name="importe" id="importe"> €
</div>
</div>
<button class="send-button" name="1button" href="">Yes</button>
<button class="send-button" name="2button" href="">No</button>
</form>
jQuery
if(is_page_template('template-landing.php')): ?>
$('#form-landing').submit(function(e){
e.preventDefault();
var form = $(this).addClass('loading');
var alert = form.find('.alert').removeClass('alert-danger alert-success').html('');
$.ajax({
url:form.data('ajax'),
type:'POST',
data:new FormData(this),
processData:false,
contentType:false,
}).done(function(data){
form[0].reset();
form.find('.btn').prop('disabled',true);
alert.addClass('alert-success').html(data);
}).fail(function(error){
alert.addClass('alert-danger').html(error.responseText);
}).always(function(){
form.removeClass('loading');
});
});
<?php endif;
?>
PHP function
function contactlanding(){
if(check_ajax_referer()){
$afrontar = sanitize_text_field($_POST['afrontar']);
$importe = sanitize_text_field($_POST['importe']);
if (isset($_POST['1button'])) {$button="First";} else{$button="Second";}
$web = parse_url(home_url(),PHP_URL_HOST);
$message = '<p><strong>Afrontar:</strong> '.$afrontar.'</p>';
$message .= '<p><strong>Importe:</strong> '.$importe.'</p>';
$message .= '<p><strong>Button:</strong> '.$button.'</p>';
$headers = 'MIME-Version:1.0'."\r\n";
$headers .= 'Content-type:text/html;charset=utf-8'."\r\n";
$headers .= 'From:noreplay#'.$web."\r\n";
$headers .= 'Reply-To:'.$email."\r\n";
$send = mail(get_bloginfo('admin_email'),'Mensaje enviado desde '.$web,$message,$headers);
if($send==true){
echo 'Gracias, tu mensaje se ha enviado correctamente.';exit;
}
}
http_response_code(400);echo 'Algo salió mal, por favor intenta más tarde.';exit;
}
You can store the action in an hidden input.
Your server will receive the data, and you will be able to read it. Next, a very simple approach to show you the way :
$('.send-button').on('click', function (){ $(this).closest('form').find('[name="action"]').val($(this).data('submit'))
})
$('form').on('submit', function(evt) {
// form content :
console.log($(this).serialize());
// prevent form submission for the demo
evt.preventDefault();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input type="text" name="firstname" value="Johon" />
<input type="hidden" name="action" value="" />
<button class="send-button" name="1button" href="" data-submit="yes">Yes</button>
<button class="send-button" name="2button" href="" data-submit="no">No</button>
</form>

Sending email in PHP using AJAX

I am trying to send email in PHP using AJAX in a simple contact form. I have the following codes for a simple form, PHP code for submit button and AJAX script.
When I am trying to send email it is not sending any email and always firing the AJAX error msg. I am not very well in AJAX integration with PHP.
Below is my code
<form method="post" class="myform" action="">
<input type="text" name="name" placeholder="Your Name" required><br>
<input type="email" name="email" placeholder="Your Email" required><br>
<textarea rows="4" cols="20" name="message" placeholder="Your Message"></textarea><br>
<input type="submit" name="submit" value="Send"> <span class="output_message"></span>
</form>
<?php
if (isset($_POST['submit'])) {
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
$message = $_REQUEST['message'];
// Set your email address where you want to receive emails.
$to = 'mymail#gmail.com';
$subject = 'Contact Request From Website';
$headers = "From: ".$name." <".$email."> \r\n";
$send_email = mail($to,$subject,$message,$headers);
echo ($send_email) ? 'success' : 'error';
}?>
<script>
$(document).ready(function() {
$('.myform').on('submit',function(){
// Add text 'loading...' right after clicking on the submit button.
$('.output_message').text('Loading...');
var form = $(this);
$.ajax({
url: form.attr('action'),
method: form.attr('method'),
data: form.serialize(),
success: function(result){
if (result == 'success'){
$('.output_message').text('Message Sent!');
} else {
$('.output_message').text('Error Sending email!');
}
}
});
// Prevents default submission of the form after clicking on the submit button.
return false;
});
});
</script>
I would move the php part to another file:
<form method="post" class="myform" action="">
<input type="text" name="name" placeholder="Your Name" required><br>
<input type="email" name="email" placeholder="Your Email" required><br>
<textarea rows="4" cols="20" name="message" placeholder="Your Message"></textarea><br>
<input type="submit" name="submit" value="Send"> <span class="output_message"></span>
</form>
<script>
$(document).ready(function() {
$('.myform').on('submit',function(){
// Add text 'loading...' right after clicking on the submit button.
$('.output_message').text('Loading...');
var form = $(this);
$.ajax({
url: "email.php",
method: form.attr('method'),
data: form.serialize(),
success: function(result){
if (result == 'success'){
$('.output_message').text('Message Sent!');
} else {
$('.output_message').text('Error Sending email!');
}
}
});
// Prevents default submission of the form after clicking on the submit button.
return false;
});
});
</script>
And in another email.php
<?php
if (isset($_POST['submit'])) {
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
$message = $_REQUEST['message'];
// Set your email address where you want to receive emails.
$to = 'mymail#gmail.com';
$subject = 'Contact Request From Website';
$headers = "From: ".$name." <".$email."> \r\n";
$send_email = mail($to,$subject,$message,$headers);
echo ($send_email) ? 'success' : 'error';
}?>
You must be stop the default flow of that form by using event.preventDefault(); and you can pass the form as multipart/formdata or form-data and check the developer tools -> network -> fetch/xhr -> payload/ formdata. then you create a seperate page in php and do the mail process in that page and change the form action link to that page
In html
<form method="post" class="myform" action="mail.php">
<input type="text" name="name" placeholder="Your Name"><br>
<input type="email" name="email" placeholder="Your Email"><br>
<textarea rows="4" cols="20" name="message" placeholder="Your Message"></textarea><br>
<input type="submit" name="submit" value="Send"> <span class="output_message"></span>
</form>
<script>
$(document).on('submit', '.myform', function(e){
e.preventDefault();
// Add text 'loading...' right after clicking on the submit button.
$('.output_message').text('Loading...');
var form = $(this);
$.ajax({
url: form.attr('action'),
method: form.attr('method'),
data: new FormData($(".myform")[0]),
dataType: 'json',
processData: false,
contentType: false,
success: function(result){
if (result.status == 'success'){
$('.output_message').text('Message Sent!');
} else {
$('.output_message').text('Error Sending email!');
}
}
});
</script>
In php - mail.php
if (isset($_POST['submit'])) {
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
$message = $_REQUEST['message'];
// Set your email address where you want to receive emails.
$to = 'mymail#gmail.com';
$subject = 'Contact Request From Website';
$headers = "From: ".$name." <".$email."> \r\n";
$send_email = mail($to,$subject,$message,$headers);
if($send_email)
{
$response = ['status' => 'success'];
}
else
{
$response = ['status' => 'error'];
}
echo json_encode($response);
}
So, the top answer works, but as #Mithu said, for some reason it always says:
'Error Sending email!'
After 30 minutes of exploring the situation I understood that for some reason it returns from PHP not 'success' but ' success' with 2-4 spaces in front of the word 'success' or 'error'.
So, all you need is to exclude these spaces, for that we need to change 'succes' to 'this is success' and 'error' to 'this is error'(just to make spare letters in the front) and then we need to divide this string to words and to extract the last word. It will always be 'success' or 'error' regardless how much spaces the script will add or how much letters it will remove accidentally. And also you need to make another if else statement in the PHP to check FALSE instead of TRUE.
Also I've added a few lines which check if the fields are filled or not. And if they are not filled then you get a message 'Please fill in the forms.'.
So here how it looks and works for me:
Importing jquery library (you need to place it into the header):
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
HTML (you need to put it there where you want to have the contact form):
<form method="post" class="myform" action="">
<input type="text" name="name" placeholder="Your Name"><br>
<input type="email" name="email" placeholder="Your Email"><br>
<textarea rows="4" cols="20" name="message" placeholder="Your Message"></textarea><br>
<input type="submit" name="submit" value="Send"> <span class="output_message"></span>
</form>
JS (you need to put it in the footer):
<script>
$(document).ready(function() {
$('.myform').on('submit',function(){
// Add text 'loading...' right after clicking on the submit button.
$('.output_message').text('Loading...');
var form = $(this);
$.ajax({
// if it can't find email.php just chahge the url path to the full path, including your domain and all folders.
url: "email.php",
method: form.attr('method'),
data: form.serialize(),
success: function(result){
// THIS IS WHAT I HAVE ADDED TO REMOVE EXCESS SPACES
let d = result.split(" ");
let y = d.slice(-1)[0];
// THIS IS WHAT I HAVE ADDED TO REMOVE EXCESS SPACES
if (y == 'success'){
$('.output_message').text('Message Sent!');
}
else if (y == 'miss'){
$('.output_message').text('Please fill in all the fields above.');
}
else {
$('.output_message').text('Error Sending email!');
}
}
});
// Prevents default submission of the form after clicking on the submit button.
return false;
});
});
</script>
email.php (you need to create this file in the same folder where you have your index.php):
<?php
// here we check if all fields are filled.
$required = array('name', 'email', 'message');
$error = false;
foreach($required as $field) {
if (empty($_REQUEST[$field])) {
$error = true;
}
}
//if something is not filled(empty) and error is true
if ($error) {
echo 'this is miss';
}
// if everything is filled then we execute the mail function
else {
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
$message = $_REQUEST['message'];
$fullmessage = "Sender's name: ".$name."\n"."Message: \n".$message;
// Set your email address where you want to receive emails.
$to = 'contact#yourdomain.com';
$subject = 'Message from YOUR E-MAIL.COM';
$send_email = mail($to,$subject,$fullmessage,$email);
if ($send_email == false) {
echo 'this is error';
} else {
echo 'this is success';
}
}
?>
So,this code steadily works for me, but maybe it is not very proffessionaly made, because I am a begginer in JS and PHP.

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>

jquery ajax contact form redirects to contact.php instead of catching php echo and executing sucess function

I have a contact form php+jquery+HTML.the form div is hidden in index.HTML,until contact button is presses.Jquery works,Ajax call posts needed data to php,which echoes a response.The problem is when php echoes,instead of remaining on same page without refreshing,browser redirects to contact.php,where the echo is showed correctly.I think the Ajax part won't catch the response from server,although syntax is the same in all tutorials.please assist.
html part:
HTML
<div id = 'contact_form'>
<div id = 'result'></div>
<form id="contactform" action="js/contact.php" method="POST" enctype="multipart/form-data">
<div class="row">
<input id="name" class="input" name="name" type="text" required = 'true' value="" size="30" placeholder='Nome'/>
</div>
<div class="row">
<input id="email" class="input" name="email" type="text" required = 'true' value="" size="30" placeholder = 'Email'/>
</div>
<div class="row">
<textarea id="message" class="input" name="message" rows="7" cols="50" required = 'true' placeholder = 'Messagio'></textarea>
</div>
<input id="submit_button" class = 'myButton' type="submit" value="Manda messagio" />
</form>
</div>
</div>
JS
$('#submit_btn').click(function(){
var user_name = $("input#name").val();
if (user_name == "") {
$("input#name").focus().addClass('active');
return false;
}
var user_email = $("input#email").val();
if (!$("input#email").val().match(/^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/)) {
$("input#email").focus().addClass('active');
return false;
}
var msg = $("textarea#message").val();
if (message == "") {
$("textarea#message").focus().addClass('active');
return false;
}
var dataString = 'name='+ user_name + '&email=' + user_email +'message = ' + msg;
//alert (dataString);return false;
// Send the request
$.ajax({
type: "POST",
url: "contact.php",
data: dataString,
success: function(d) {
console.log(d);
}
});
return false;
});
PHP
<?php
$toEmail = "x#gmail.com";
$subject = "dal tuo sito ";
$mailHeaders = "From: " . $_POST["name"] . "<". $_POST["email"] .">\r\n";
if(mail($toEmail,$subject,$_POST["message"], $mailHeaders)) {
echo "Mail Sent";
} else {
echo "Problem in Sending Mail";
}
?>
If you want to keep the same button you can change your js.
$('#submit_btn').click(function(e){
e.preventDefault();
//YOUR CODE HERE
}
Because you used a submit type input, I recommend you change the submit input for a link like button. And also remove the action attr from the form:
HTML
Send
JS
<script>
$('#btn').on("click", function(){
//Your ajax here
//var dataString = 'name='+ user_name + '&email=' + user_email +'message = ' + msg;
//alert (dataString);return false;
// Send the request
$.ajax({
type: "POST",
url: "contact.php",
data: {name: user_name, email: user_email, message: msg}
}).done(function(response){
console.log(response);
});
});
</script>

AJAX/JQuery and PHP to send prompt without reload for a contact form

Full website: http://adamginther.com
I've used two separate tutorials to build this, one for the PHP and one for the AJAX. My goal is to build a contact form that will check for errors. If there are no errors then it will prompt users with a message saying that the message has been sent without refreshing the page.
When the website is run locally it does not display the errors until the button is pressed, when run on the server the errors are displayed on entering the page. When the contact button is pressed it loads PHP and the page goes blank.
HTML
<form action="contact.php" method="post">
<label name="firstName">Name: </label>
<input type="text" name="firstName" id="firstName">
<label class="error" for="firstName" id="name_error">I need your name.</label>
<br id="namebreak">
<br>
<label name="email" for="email" id="email_label">E-mail Address: </label>
<input type="text" name="email" id="email">
<label class="error" for="firstName" id="name_error">I need your e-mail.</label>
<br id="emailbreak">
<br>
<label name="message">Message: </label>
<textarea name="message" id="message"></textarea>
<label class="error" for="firstName" id="name_error">I need your message.</label>
<br id="messagebreak">
<br>
<input type="submit" value="Say Hello!" id="contactbutton" class="button">
JavaScript
$(function () {
$('.error').hide();
$(".button").click(function () {
$('.error').hide();
var name = $("input#firstName").val();
if (name == "") {
$("label#name_error").show();
$("input#name").focus();
$("#namebreak").hide();
return false;
}
var email = $("input#email").val();
if (email == "") {
$("label#email_error").show();
$("input#email").focus();
$("#emailbreak").hide();
return false;
}
var message = $("input#message").val();
if (message == "") {
$("label#message_error").show();
$("input#message").focus();
$("#messagebreak").hide();
return false;
}
var dataString = 'name=' + name + '&email=' + email + '&phone=' + phone;
$.ajax({
type: "POST",
url: "contact.php",
data: dataString,
success: function () {
$('#contactme').html("<div id='message'></div>");
$('#message').html("<p>Contact form submitted.</p>")
.append("<p>I will get back to you shortly.</p>")
.hide()
.fadeIn(1500, function () {
$('#message').append("<img id='checkmark' src='images/check.png' />");
});
}
});
return false;
});
});
PHP
<?php
$field_firstName = $_POST['firstName'];
$field_email = $_POST['email'];
$field_message = $_POST['message'];
$mail_to = 'gintherthegreat#gmail.com';
$subject = 'AdamGinther.com message from '.$field_firstName;
$body_message = 'From: '.$field_firstName."\n";
$body_message .= 'E-mail: ' .$field_email."\n";
$body_message .= 'Message: '.$field_message;
$headers = 'From: '.$field_email."\r\n";
$headers .= 'Reply-To: '.$field_email."\r\n";
$mail_status = mail($mail_to, $subject, $body_message, $headers);
if ($mail_status) { ?>
<script language="javascript" type="text/javascript">
$('#panel').show();
$('#output-inside').text('Thank you ' + firstName + ', I will get back to you as soon as I can.');
</script>
<?php
}
else { ?>
<script language="javascript" type="text/javascript">
$('#panel').show();
$('#output-inside').text('I am sorry ' + firstName + ', but there was a problem processing your request. I can be contacted by e-mail at GintherTheGreat#Gmail.com'); </script>
<?php
}
?>
I think you need to prevent default action of the submit button.
Use,
$(function() {
$('.error').hide();
$(".button").click(function(e) {
e.preventDefault();
// Other code
});
});
change
<form action="contact.php" method="post">
to
<form action="contact.php" method="post" id="form_id">
and change
$(".button").click(function () {
to
$('#form_id').submit(function (event) {
event.preventDefault();
...
...
Just simply change the button type from submit to button so it will not submit the form and goes to php blank page by default and call the function for u.
Try the following:
<form action="contact.php" method="post" onsubmit="return false;">
Instead of using a form, why not just have an external .php (e.g. sendmail.php) script that handles your php, and then use jQuery to handle the POST.
$.post('sendmail.php',{
mail:mail,
message:message
}, function(data) {
//Echo either "success" or "false" in the sendmail.php script
if(data == "success"){
//Do something - e.g. (alert('Message has been sent');)
}else{
//Do something
}
});

Categories