I have decided I'd like to incorporate localStorage on my WordPress contact page form. I am using the jQuery and PHP script below to store unsent text within the form and then once completed send the information. The script works for the most part it does send and give error messages when not fully completed. The problem I'm encountering is when the information in the form fields are correct and sent the fields are not clearing after the browser refresh.
I've tried modifying this line of script which is suppose to clear the fields but I've had no luck .
//My field id's
var formElements = $('#name, #message, #email');
//on form submit remove item from localstorage
formElements.submit(function(e){
e.preventDefault();
formElements.each(function(){
localStorage.removeItem($(this).attr('id'));
});
});
PHP Script:
<?
//response generation function
$response = "";
//function to generate response
function my_contact_form_generate_response($type, $message){
global $response;
if($type == "success") $response = "<div class='success'>{$message}</div>";
else $response = "<div class='error'>{$message}</div>";
}
//response messages
$not_human = "Human verification incorrect.";
$missing_content = "Please supply all information.";
$email_invalid = "Email Address Invalid.";
$message_unsent = "Message was not sent. Try Again.";
$message_sent = "Thanks! Your message has been sent.";
//user posted variables
$name = $_POST['message_name'];
$email = $_POST['message_email'];
$message = $_POST['message_text'];
$human = $_POST['message_human'];
//php mailer variables
$to = get_option('admin_email');
$subject = "Someone sent a message from ".get_bloginfo('name');
$headers = 'From: '. $email . "\r\n" .
'Reply-To: ' . $email . "\r\n";
if(!$human == 0){
if($human != 2) my_contact_form_generate_response("error", $not_human); //not human!
else {
//validate email
if(!filter_var($email, FILTER_VALIDATE_EMAIL))
my_contact_form_generate_response("error", $email_invalid);
else //email is valid
{
//validate presence of name and message
if(empty($name) || empty($message)){
my_contact_form_generate_response("error", $missing_content);
}
else //ready to go!
{
$sent = wp_mail($to, $subject, strip_tags($message), $headers);
if($sent) my_contact_form_generate_response("success", $message_sent); //message sent!
else my_contact_form_generate_response("error", $message_unsent); //message wasn't sent
}
}
}
}
else if ($_POST['submitted']) my_contact_form_generate_response("error", $missing_content);
?>
jQuery Script :
jQuery(function($) {
var formElements = $('#name, #message, #email');
formElements.on('keyup', function(){
//put value in the localStorage
localStorage.setItem($(this).attr('id'), $(this).val());
});
//on form submit remove item from localstorage
formElements.submit(function(e){
e.preventDefault();
formElements.each(function(){
localStorage.removeItem($(this).attr('id'));
});
});
//if form not submitted and page refreshed get and set the values
formElements.each(function(){
$(this).val(localStorage.getItem($(this).attr('id')));
});
});
Your call to set formElements is not correct. It should be:
var formElements = $('#name, #message, #email');
The list of selectors should all be in one string, not separate arguments to jQuery.
Related
I need some help with my php. I am creating an ajax php mailer system, and I'm trying to figure out two things, I want to make it so when the email is successfully sent, to redirect to another page
and, I have another problem, when I send an email, the 'from' part has a name of my web host username, and I want to change it to my email, anyone know how to do that with php, or ajax.
php file
<?php
// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$name = strip_tags(trim($_POST["name"]));
$phone = trim($_POST["tel"]);
$time = trim($_POST["time"]);
$method = trim($_POST["method"]);
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$message = trim($_POST["message"]);
// Check that data was sent to the mailer.
if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
http_response_code(400);
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
// Set the recipient email address.
// FIXME: Update this to your desired email address.
$recipient = "WebInquiry#ThePPCGroup.Com";
// Set the email subject.
$subject = "New contact from $name";
$msg = "Thank you for contacting ThePPCGroup.\nSomeone will contact you shortly. Please let us know the best time to reach you, and if phone or email is better.\nThePPCGroup\n855-539-4742\nWebInquiry#ThePPCGroup.Com\nWWW.ThePPCGroup.Com";
// Build the email content.
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Phone: $phone\n\n";
$email_content .= "Prefered Time: $time\n\n";
$email_content .= "Prefered Method: $method\n\n";
$email_content .= "Message:\n$message\n";
// Build the email headers.
$email_headers = "From: $name <$email>";
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
http_response_code(200);
mail($email, "Thank You!", $msg, "WebInquiry#ThePPCGroup.Com")
} else {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "Oops! Something went wrong and we couldn't send your message.";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>
ajax file
function sendEmail() {
var form = $('#ajax-contact');
var formMessages = $('#form-messages');
var formData = $(form).serialize();
$(form).submit(function(event) {
event.preventDefault();
});
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
$(formMessages).text(response);
$('#name').val('');
$('#email').val('');
$('#tel').val('');
$('#time').val('');
$('#method').val('');
$('#message').val('');
window.location = 'http://www.theppcgroup.com/thank-you.html';
})
.fail(function(data) {
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
}
if ($('#submit').on('click', function() {
sendEmail();
}));
You can return an array to the ajax function like this:
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
http_response_code(200);
mail($email, "Thank You!", $msg, "WebInquiry#ThePPCGroup.Com");
$response = array('status': true, 'message': "Thank You!");
} else {
// Set a 500 (internal server error) response code.
http_response_code(500);
$response = array('status': false, 'message': "Oops! Something went wrong and we couldn't send your message.");
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
$response = array('status': false, 'message': "There was a problem with your submission, please try again.");
}
return json_encode($response);
and in ajax
.done(function(response) {
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
$(formMessages).text(response.message);
$('#name').val('');
$('#email').val('');
$('#tel').val('');
$('#time').val('');
$('#method').val('');
$('#message').val('');
if (response.status == true){
window.location = 'http://www.theppcgroup.com/thank-you.html';
}
})
I am building a set of forms shortcodes in Wordpress. I have given up trying to get the form processing script into a shortcode and am just going to make it available to all pages.
There is however an echo that puts out the response of the form which I want to put into it's own shortcode.
<?php echo $response; ?>
This needs to go at the top of the form so that validation messages appear in the right place.
Total form processing code:
<?php
//response generation function
$response = "";
//function to generate response
function my_contact_form_generate_response($type, $message){
global $response;
if($type == "success") $response = "<div class='callout success'><p>{$message}</p></div>";
else $response = "<div class='callout error'><p>{$message}</p></div>";
}
// response messages
$not_human = "Please fill out the human verification field to prove you are not a spam robot. A number 2 will do the job nicely.";
$missing_content = "It looks like we are missing something. Please chek the form below.";
$email_invalid = "That email Address doesn't look quite right.";
$message_unsent = "Your message wasn't sent. Please have another go. If it still doesn't work then please call us using the number supplied.";
$message_sent = "Thank you for your enquiry. We will be in contact shortly.";
// user posted variables
$business_name = $_POST['message_business_name'];
$first_name = $_POST['message_first_name'];
$last_name = $_POST['message_last_name'];
$email = $_POST['message_email'];
$phone = $_POST['message_phone'];
$human = $_POST['message_human'];
$location = $_POST['location'];
$message_opt_in = $_POST['message_opt_in'];
$optin = "";
if ($message_opt_in == "on"){
$optin = "The user has opted in to marketing emails";
}
else {
$optin = "!!!!!!!!!!!!!!!!!!!!!!\n\n The user has NOT opted in to marketing emails! \n\n!!!!!!!!!!!!!!!!!!!!!!\n\n";
}
$body = "$optin \n\n\n\n This message was sent from xxx.com $location\n\nBusiness name: $business_name \nName: $first_name \nName: $last_name \nEmail: $email \nPhone: $phone";
//php mailer variables
$to ="xxx#xxx.com";
$subject = "Someone sent a message from ".get_bloginfo('name');
$headers = 'From: '. $email . "\r\n" .
'Reply-To: ' . $email . "\r\n";
if(!$human == 0){
if($human != 2) my_contact_form_generate_response("error", $not_human); //not human!
else {
//validate email
if(!filter_var($email, FILTER_VALIDATE_EMAIL))
my_contact_form_generate_response("error", $email_invalid);
else //email is valid
{
//validate presence of name and message
if(empty($business_name) || empty($first_name) || empty($email)){
my_contact_form_generate_response("error", $missing_content);
}
else //ready to go!
{
$sent = wp_mail($to, $subject, strip_tags($body), $headers);
if($sent) my_contact_form_generate_response("success", $message_sent); //message sent!
else my_contact_form_generate_response("error", $message_unsent); //message wasn't sent
}
}
}
}
else if ($_POST['submitted']) my_contact_form_generate_response("error", $missing_content);
?>
<?php echo $response; ?>
I have tried amongst other things that would probably make a PHP dev laugh.
function form_response(){
echo $response;
}
function form_response(){
echo '<?php echo "$response"; ?>';
}
Disclaimer I'm not a PHP developer as you can probably tell.
In the my_contact_form_generate_response function, you can do return $response; at the very bottom before the closing } for the function.
Then, you can do echo my_contact_form_generate_response($type, $message); and it will echo the return value, which will be $response in this case.
Try to change
else if ($_POST['submitted']) my_contact_form_generate_response("error", $missing_content);
To
else if ($_POST['submitted']){
$response = 'Some things';
$response .= my_contact_form_generate_response("error", $missing_content);
return $response;
}
I had to call $response from global
function form_response(){
echo $GLOBALS["response"];
}
I've found a template that I want to edit and it already has a nice looking contact form. After hitting the submit button I'm getting a thank you message but I would like to redirect to another page where the message will appear so I can use it for conversion tracking.
Could someone be of assistance what should I do as my current code looks like this:
<?php
$firstname = '';
$number = '';
$message = '';
$email = '';
if($_POST) {
// collect all input and trim to remove leading and trailing whitespaces
$firstname = trim($_POST['first_name']);
$number = trim($_POST['phone']);
$message = trim($_POST['message']);
$email = trim($_POST['email']);
$errors = array();
// Validate the input
if (strlen($firstname) == 0)
array_push($errors, "Please enter your name");
if (strlen($number) == 0)
array_push($errors, "Please specify your number");
if (strlen($message) == 0)
array_push($errors, "Please enter the details of your message");
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
array_push($errors, "Please specify a valid email address");
// If no errors were found, proceed with storing the user input
if (count($errors) == 0) {
//completion message into array
$to = 'me#mymailzz.com'; // note the comma
// the email subject ( modify it as you wish )
$subject = "Enquiry From website";
// the mail message ( add any additional information if you want )
$msg = "Quote From website:\n-------------------------------------------\n Name: $firstname \n Number: $number \n Email: $email \n Message: $message \n-------------------------------------------";
//function to send email
try {
mail($to, $subject, $msg, "From: $email\r\nReply-To: $email\r\nReturn-Path: $email\r\n");
$return1 = "Thank You for sending your message, we will be in touch within 48-72 hours";
array_push($errors, $return1);
$formsubmit = 1;
}catch(Exception $e){
$return3 = "<center><p><b>Your message did not get sent due to an error. Please try again. Caught Exception {$e->getMessage()}</center>";
array_push($errors, $return3);
$formsubmit = 0;
}
}
//Prepare errors for output
$output = '';
foreach($errors as $val) {
$output .= "<p class='output'>$val</p>";
}
}
?>
Replace the line:
$return1 = "Thank You for sending your message, we will be in touch within 48-72 hours";
With something like this:
header('Location: some_page.php');
exit;
And then you can remove these lines as they become obsolete:
array_push($errors, $return1);
$formsubmit = 1;
That will redirect to some_page.php instead of printing that message.
To store the message across pages, do this at the start of your script:
session_start();
Instead of storing messages in a normal variable, store it in a session variable, e.g.:
$_SESSION['message'] = 'Your message here';
At the end of your script:
if ($formsubmit == 1) {
header('Location: your-file.php');
}
In your-file.php:
<?php
session_start();
echo $_SESSION['message'];
Just made a change in your try code and insert redirect fuunction
try {
mail($to, $subject, $msg, "From: $email\r\nReply-To: $email\r\nReturn-Path: $email\r\n");
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.location.href='next_page.php'
</SCRIPT>");
}
How about you trace in your web template where you have <form action="#"> and proceed with help from a previously similar asked question found here
I'm using code from another source but it's very different to what I'm used to coding when using standard HTML/PHP websites. Wordpress seems to have a mind of it's own. Basically I need the contact form's PHP to send the name and email within the body text of the email and not just the persons message. Currently all that comes through is the persons message.
<?php
//response generation function
$response = "";
//function to generate response
function my_contact_form_generate_response($type, $message){
global $response;
if($type == "success") $response = "<div class='success'>{$message}</div>";
else $response = "<div class='error'>{$message}</div>";
}
//response messages
$not_human = "Human verification incorrect.";
$missing_content = "Please Fill in all Required Fields.";
$email_invalid = "Your Email Address is Invalid.";
$message_unsent = "Message was not sent. Please Try Again.";
$message_sent = "Thanks! Your message has been sent.";
//user posted variables
$name = $_POST['message_name'];
$email = $_POST['message_email'];
$message = $_POST['message_text'];
$human = $_POST['message_human'];
//php mailer variables
$to = get_option('admin_email');
$subject = "New Enquiry Through Mon Voyage Website";
$headers = 'From: '. $email . "\r\n" .
'Reply-To: ' . $email . "\r\n";
if(!$human == 0){
if($human != 2) my_contact_form_generate_response("error", $not_human); //not human!
else {
//validate email
if(!filter_var($email, FILTER_VALIDATE_EMAIL))
my_contact_form_generate_response("error", $email_invalid);
else //email is valid
{
//validate presence of name and message
if(empty($name) || empty($message)){
my_contact_form_generate_response("error", $missing_content);
}
else //ready to go!
{
$sent = wp_mail($to, $subject, strip_tags($message), $headers);
if($sent) my_contact_form_generate_response("success", $message_sent); //message sent!
else my_contact_form_generate_response("error", $message_unsent); //message wasn't sent
}
}
}
}
else if ($_POST['submitted']) my_contact_form_generate_response("error", $missing_content);
?>
Any ideas?
add this in just before if(!$human == 0){:
$message.='Name: '.$name.'email: '$email;
this is all standard php form checking, 1. function to display a reponse 2. check the $_POST data 3. fail if errors in place 4. if no errors, send email. Put a few echo's in there and play around with it to see what is happening.
This does not solve the issue you are having directly but instead of writing the code yourself you could use Contact form 7 plugin instead. It will save you time and is very quick to implement.
You can get the plugin from this url.
Here is the documentation for implementing the plugin.
You can add a contact form by adding the short code generated by the plugin to the page you want it to appear like this:
[contact-form-7 id="1234" title="Contact form 1"]
I'm trying to make a php mail form display a success message upon a successful submit.
I'm new to php and I'm not sure how to make this work.
As it sits now, after submit, the site just reloads at the top of the page. I'd like it to refresh at the contact div and display a success message.
Contact div html:
<div class="contact-wrapper" >
<div class="contact">
<div class="contact-left" id="contact">
<?php
if (isset($_REQUEST['email'])) {
echo "Thank you for your message.";
}
$mail_form = include('php/mail_form.php'); ?>
</div> <!-- end div contact -->
Contact from PHP:
<?php
function spamcheck($field)
{
//filter_var() sanitizes the e-mail
//address using FILTER_SANITIZE_EMAIL
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
//filter_var() validates the e-mail
//address using FILTER_VALIDATE_EMAIL
if(filter_var($field, FILTER_VALIDATE_EMAIL))
{
return TRUE;
}
else
{
return FALSE;
}
}
if (isset($_REQUEST['email']))
{//if "email" is filled out, proceed
//check if the email address is invalid
$mailcheck = spamcheck($_REQUEST['email']);
if ($mailcheck==FALSE)
{
echo "Invalid input";
}
else
{//send email
$email = $_REQUEST['email'] ;
$subject = $_REQUEST['subject'] ;
$message = $_REQUEST['message'] ;
mail("idc615#gmail.com", "Subject: $subject",
$message, "From: $email" );
header("location: index.php");
}
}
?>
Try this code... You need to halt your script for some time so that user can see success or failure message. Without sleep user will not be able to see message as header will execute immediately.
if(mail("idc615#gmail.com", "Subject: $subject",$message, "From: $email" )){
echo "Thank you for your message";
sleep(2); // sleep for 2 seconds. Enough to display success message
//header will execute after 2000ms(2s)
header("location: index.php");
}else{
echo "Unable to send message";
sleep(2); // sleep for 2 seconds
header("location: index.php");
}
or try code given below:
in Contact from PHP
if(mail("idc615#gmail.com", "Subject: $subject",$message, "From: $email" )){
header("location: index.php?status=1");
}else{
header("location: index.php?status=0");
}
in index.php
if(isset($_GET['status'])){
$status = $_GET['status'];
if($status == 1){
echo "Thank you for your message";
}else if($status == 0){
echo "Unable to send message";
}
}
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
$message = mysql_real_escape_string($_POST['message']);
if(isset($_POST['contactrgtr']))
{
$query = "insert into contact_us(name,email,message)values('$name','$email','$message')";
$res = mysql_query($query);
if($res){
$message = 'Your Message Successfully Sent';
include_once('contact.php'); } `
Then in contact.php page you have to define <?php $message ?>.