Contact form - cannot get email to send - javascript

I am trying to create a basic form to send an email and here is how it looks:
http://www.unitedserbians.com/contact_us.html
I have everything working and buttoned up, except I cannot get the actual email to be sent once the form has completed processing. My function executes as my field validations work great and I can see the correct values are being grabbed from the form by un-commenting the JAVA script code "alert (dataString);return false;" and even the .ajax executes because I get "Contact Form Sent! We will be in touch soon." message displayed but the actual email never gets sent. I am guessing that something is missing in the process.php file. I cannot trace to see where the issue occurs or if my process.php ever executes. Should the file live in the same directory with JAVA script? or at main directory bin folder? Or is there something I am blindly missing in the process code? Can someone spot what am I missing please? Much appreciated in advance.
HTML:
<div class="content">
<div class="content_resize">
<div class="mainbar">
<div class="article">
<h2><span>Send us E-Mail</span></h2>
<div id="contact_form">
<form action="" form name="contact">
<fieldset>
<ol>
<li>
<label for="name" id="name_label">Your Full Name</label>
<input type="text" name="name" id="name" size="30" value="" class="text-input" />
<label2 class="error" for="name" id="name_error">This field is required.</label2>
</li>
<li>
<label for="email" id="email_label">Your Email Address</label>
<input type="text" name="email" id="email" size="30" value="" class="text-input" />
<label2 class="error" for="email" id="email_error">This field is required.</label2>
</li>
<li>
<label for="website id="phone_label">Your Phone Number</label>
<input type="text" name="phone" id="phone" size="30" value="" class="text-input" />
<label2 class="error" for="phone" id="phone_error">This field is required.</label2>
</li>
<li>
<label for="message">Your Message</label>
<textarea id="message" name="message" rows="8" cols="50"></textarea>
</li>
<li>
<input type="submit" name="imageField" id="submit_btn" src="images/submit.gif" class="send" />
</li>
</ol>
</fieldset>
</form>
</div>
</div>
</div>
JAVA script:
$(function() {
$('.error').hide();
$(".send").click(function() {
// validate and process form here
$('.error').hide();
var name = $("input#name").val();
if (name == "") {
$("label2#name_error").show();
$("input#name").focus();
return false;
}
var email = $("input#email").val();
if (email == "") {
$("label2#email_error").show();
$("input#email").focus();
return false;
}
var phone = $("input#phone").val();
if (phone == "") {
$("label2#phone_error").show();
$("input#phone").focus();
return false;
}
var message = $("textarea#message").val();
var dataString = 'name='+ name + '&email=' + email + '&phone=' + phone + '&message=' + message;
// alert (dataString);
// return false;
$.ajax({
type: "POST",
url: "bin/process.php",
data: dataString,
success: function() {
$('#contact_form').html("<div id='send_message'></div>");
$('#send_message').html("<h2>Contact Form Sent!</h2>")
.append("<p>We will be in touch soon.</p>");
}
});
return false;
});
});
PHP:
<?php
$email_to = "XXXXX#gmail.com";
$email_subject = "Message sent using contact form.";
$name = $_POST['name']; // required
$email_from = $_POST['email']; // required
$phone = $_POST['phone']; // required
$message = $_POST['message'];
$email_message .= "Full Name: ".clean_string($name)."\n";
$email_message .= "Email: ".clean_string($email_from)."\n";
$email_message .= "Phone Number: ".clean_string($phone)."\n";
$email_message .= "Message: ".clean_string($message)."\n";
// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
#mail($email_to, $email_subject, $email_message, $headers);
?>

One possibility is that your host doesn't like the $email_from address. I think most hosts are restrictive about sending using a From address that isn't associated with that host (this is so to not enable spammers). Try using no-reply#yourdomain.com or something like that, or even better an address that really exists, as your From address. The Reply-To can still be the address the user enters (after you check that it is valid).

Related

Data from new HTML form input field not being passed to email using PHP and JavaScript

This is my first post on the site. I added a new input field to a previously working HTML contact form in order to collect the user’s street address. Although all other input fields continue to pass data to the email generated after the form is submitted, data is not being passed to the email with the street address. I have copied below the associated HTML, PHP, and JavaScript files, as well as an example of what data is now sent to the email.
I truly appreciate any help with what I am doing wrong. I have spent over 8 hours trying to solve this problem, but so far have been unsuccessful. Thank you!
Here is an example of the data now being placed into the email generated. Notice that the only data NOT being passed is the text that was input into the street address field of the contact form (blank).
Name: Tim Spyridon
Address:
Phone Number: 513-662-1464
Message:
Made major changes to PHP script. This may work!
Here is the HTML code used for the contact form:
<!-- Form Starts -->
<div id="contact_form">
<div class="form-group">
<label>Name <span class="required">*</span></label>
<input placeholder="Your Name" type="text" name="name" class="form-control input-field" required>
<label>Street Address and City <span class="required">*</span></label>
<input placeholder="Your Street Address and City" type="text" name="address" class="form-control input-field" required>
<label>Email Address <span class="required">*</span></label>
<input placeholder="Your Email Address" type="email" name="email" class="form-control input-field" required>
<label>Phone Number including Area Code <span class="required">*</span></label>
<input placeholder="Your 10-Digit Phone Number" type="tel" name="phone" class="form-control input-field" required>
<label>Message <span class="required">*</span></label>
<textarea placeholder="Type your message here ..." name="message" id="message" class="textarea-field form-control" rows="3" required></textarea>
</div>
<div class="text-right">
* Required Field
</div>
<button type="submit" id="submit_btn" value="Submit" class="btn center-block">Send message</button>
</div>
Here is my JavaScript code from a file called contact.js:
"use strict";
jQuery(document).ready(function($) {
$("#submit_btn").on("click", function() {
var proceed = true;
//simple validation at client's end
//loop through each field and we simply change border color to red for invalid fields
$("#contact_form input[required], #contact_form textarea[required]").each(function() {
$(this).css('background-color', '');
if (!$.trim($(this).val())) { //if this field is empty
$(this).css('background-color', '#FFDEDE'); //change border color to #FFDEDE
proceed = false; //set do not proceed flag
}
//check invalid email
var email_reg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if ($(this).attr("type") === "email" && !email_reg.test($.trim($(this).val()))) {
$(this).css('background-color', '#FFDEDE'); //change border color to #FFDEDE
proceed = false; //set do not proceed flag
}
});
if (proceed) //everything looks good! proceed...
{
//get input field values data to be sent to server
var post_data = {
'user_name': $('input[name=name]').val(),
'user_address': $('input[name=address]').val(),
'user_email': $('input[name=email]').val(),
'phone': $('input[name=phone]').val(),
'msg': $('textarea[name=message]').val()
};
//Ajax post data to server
$.post('php/sendmail.php', post_data, function(response) {
if (response.type === 'error') { //load json data from server and output message
var output = '<br><br><div class="error">' + response.text + '</div>';
} else {
var output = '<br><br><div class="success">' + response.text + '</div>';
//reset values in all input fields
$("#contact_form input, #contact_form textarea").val('');
}
$('html, body').animate({scrollTop: $("#contact_form").offset().top-50}, 2000);
$("#contact_results").hide().html(output).slideDown();
}, 'json');
}
});
//reset previously set border colors and hide all message on .keyup()
$("#contact_form input[required=true], #contact_form textarea[required=true]").keyup(function() {
$(this).css('background-color', '');
$("#result").slideUp();
});
});
Here is my PHP script from a file called sendmail.php:
<?php
if($_POST)
{
$to_email1 = "kim#twotailsup.com"; //Recipient email, Replace with own email here
$to_email2 = "tim#twotailsup.com"; //Recipient email, Replace with own email here
$email_subject = "Message from Website Contact Form";
//check if its an ajax request, exit if not
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
$output = json_encode(array( //create JSON data
'type'=>'error',
'text' => 'Sorry Request must be Ajax POST'
));
die($output); //exit script outputting json data
}
//Sanitize input data using PHP filter_var().
$user_name = filter_var($_POST["user_name"], FILTER_SANITIZE_STRING);
$user_address = filter_var($_POST['user_address'], FILTER_SANITIZE_STRING);
$user_email = filter_var($_POST["user_email"], FILTER_SANITIZE_EMAIL);
$phone = filter_var($_POST["phone"], FILTER_SANITIZE_NUMBER_INT);
$message = filter_var($_POST["msg"], FILTER_SANITIZE_STRING);
$message_body = "Name: " . $user_name . "\n"
. "Address: " . $user_address . "\n"
. "Email: " . $user_email . "\n"
. "Phone Number: " . $phone . "\n"
. "Message: " . "\n" . $message;
//proceed with PHP email.
$headers = 'From: '.$user_name.'' . "\r\n" .
'Reply-To: '.$user_email.'' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$send_mail = mail($to_email1, $email_subject, $message_body, $headers);
$send_mail = mail($to_email2, $email_subject, $message_body, $headers);
if(!$send_mail)
{
//If mail couldn't be sent output error. Check your PHP email configuration (if it ever happens)
$output = json_encode(array('type'=>'error', 'text' => '<p>Could not send mail! Please check your PHP mail configuration.</p>'));
die($output);
}else{
$output = json_encode(array('type'=>'message', 'text' => '<div class="alert alert-success" role="alert">
Hi '.$user_name .', Thank you for your message! We will get back to you soon.</div>'));
die($output);
}
}
?>
In support of the comment made last night (above ) here is the test version of the above script which appears to work perfectly well in terms of the newly added message field. There are comments at places where things were changed - some semantic, others functional.
<?php
if( $_POST ){
# Simple Boolean to switch between live & test mode
# whilst testing that this script does or does not
# function correctly.
$b_live=false;
$to_email1 = "kim#twotailsup.com"; //Recipient email, Replace with own email here
$to_email2 = "tim#twotailsup.com"; //Recipient email, Replace with own email here
$email_subject = "Message from Website Contact Form";
//check if its an ajax request, exit if not
if( !isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) AND strtolower( $_SERVER['HTTP_X_REQUESTED_WITH'] ) != 'xmlhttprequest' ) {
$output = json_encode(array( //create JSON data
'type'=>'error',
'text' => 'Sorry Request must be Ajax POST'
));
die($output); //exit script outputting json data
}
//Sanitize input data using PHP filter_var().
$user_name = filter_var($_POST["user_name"], FILTER_SANITIZE_STRING);
$user_address = filter_var($_POST['user_address'], FILTER_SANITIZE_STRING);
$user_email = filter_var($_POST["user_email"], FILTER_SANITIZE_EMAIL);
$phone = filter_var($_POST["phone"], FILTER_SANITIZE_NUMBER_INT);
$message = filter_var($_POST["msg"], FILTER_SANITIZE_STRING);
$message_body = "Name: " . $user_name . "\n"
. "Address: " . $user_address . "\n"
. "Email: " . $user_email . "\n"
. "Phone Number: " . $phone . "\n"
. "Message: " . "\n" . $message;
//proceed with PHP email.
$headers = 'From: '.$user_name.'' . "\r\n" .
'Reply-To: '.$user_email.'' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
# If the script is live, attempt to send the emails
if( $b_live ){
$send_mail = mail($to_email1, $email_subject, $message_body, $headers);
$send_mail = mail($to_email2, $email_subject, $message_body, $headers);
}else{
# emulate either a success or failure randomly
# to aid testing of ajax callback
$send_mail=mt_rand(0,1);
# you can verify the message is being populated
$_POST['MESSAGE']=$message;
$_POST['TIME']=date( DATE_ATOM );
file_put_contents( __DIR__ . '/ajax.log', json_encode( $_POST ) . PHP_EOL, FILE_APPEND );
}
if(!$send_mail){
//If mail couldn't be sent output error. Check your PHP email configuration (if it ever happens)
$output = json_encode(array('type'=>'error', 'text' => '<p>Could not send mail! Please check your PHP mail configuration.</p>'));
die( $output );
}else{
$output = json_encode(array('type'=>'message', 'text' => '<div class="alert alert-success" role="alert">
Hi '.$user_name .', Thank you for your message! We will get back to you soon.</div>'));
die( $output );
}
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<script src='//code.jquery.com/jquery-latest.js'></script>
<title>Contact</title>
</head>
<body>
<!--
The `label` attribute **must** be associated with whichever form element
it is supposed to reference. This can be done either by including the
`for` attribute in the label with the input element's ID OR the form element
must be within the label itself - as shown below.
-->
<div id="contact_form">
<div class="form-group">
<label>
Name <span class="required">*</span>
<input placeholder="Your Name" type="text" name="name" class="form-control input-field" required />
</label>
<label>
Street Address and City <span class="required">*</span>
<input placeholder="Your Street Address and City" type="text" name="address" class="form-control input-field" required />
</label>
<label>
Email Address <span class="required">*</span>
<input placeholder="Your Email Address" type="email" name="email" class="form-control input-field" required />
</label>
<label>
Phone Number including Area Code <span class="required">*</span>
<input placeholder="Your 10-Digit Phone Number" type="tel" name="phone" class="form-control input-field" required />
</label>
<label>
Message <span class="required">*</span>
<textarea placeholder="Type your message here ..." name="message" id="message" class="textarea-field form-control" rows="3" required /></textarea>
</label>
</div>
<div class="text-right">
* Required Field
</div>
<button type="submit" id="submit_btn" value="Submit" class="btn center-block">Send message</button>
</div>
<!--
Added this DIV to allow output to be rendered
-->
<div id='contact_results'></div>
<script>
"use strict";
jQuery(document).ready(function($) {
$("#submit_btn").on("click", function() {
var proceed = true;
//simple validation at client's end
//loop through each field and we simply change border color to red for invalid fields
$("#contact_form input[required], #contact_form textarea[required]").each(function() {
$(this).css('background-color', '');
if (!$.trim($(this).val())) { //if this field is empty
$(this).css('background-color', '#FFDEDE'); //change border color to #FFDEDE
proceed = false; //set do not proceed flag
}
//check invalid email
var email_reg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if ($(this).attr("type") === "email" && !email_reg.test($.trim($(this).val()))) {
$(this).css('background-color', '#FFDEDE'); //change border color to #FFDEDE
proceed = false; //set do not proceed flag
}
});
if (proceed) //everything looks good! proceed...
{
//get input field values data to be sent to server
var post_data = {
'user_name': $('input[name=name]').val(),
'user_address': $('input[name=address]').val(),
'user_email': $('input[name=email]').val(),
'phone': $('input[name=phone]').val(),
'msg': $('textarea[name=message]').val()
};
//Ajax post data to server
/*
*****************************************************
This is the ONLY change made in the Javascript
*****************************************************
*/
const _URL=location.href; // 'php/sendmail.php'
$.post( _URL, post_data, function(response) {
if (response.type === 'error') { //load json data from server and output message
var output = '<br><br><div class="error">' + response.text + '</div>';
} else {
var output = '<br><br><div class="success">' + response.text + '</div>';
$("#contact_form input, #contact_form textarea").val('');
}
$('html, body').animate({scrollTop: $("#contact_form").offset().top-50}, 2000);
$("#contact_results").hide().html(output).slideDown();
}, 'json');
}
});
//reset previously set border colors and hide all message on .keyup()
$("#contact_form input[required=true], #contact_form textarea[required=true]").keyup(function() {
$(this).css('background-color', '');
$("#result").slideUp();
});
});
</script>
</body>
</html>
With this I could not replicate the issues stated in the question: The $message variable is populated and can be inspected in the console or the ajax.log file that is generated in test mode.

Contact form that doesn't refresh page on submit while using Wordpress

I have setup the following code to make a contact form that doesn't refresh the page when submitted.
HTML:
<form method="POST" id="contact-form">
<div class="contact-element flex-row">
<input class="" type="text" name="name" placeholder="Name" id="name" Required>
<input class="" type="text" name="email" placeholder="Email Address" id="email" Required>
</div>
<input class="" type="text" name="subject" placeholder="Subject" id="subject" Required>
<textarea type="text" name="message" rows="5" placeholder="Message" id="message" Required></textarea>
<input class="contact-submit" id="submit" name="submit" type="submit" value="Submit">
<input type="hidden" name="action" value="form-action">
</form>
JavaScript/AJAX request:
$("#contact-form").submit(function(event) {
event.preventDefault();
var $form = $( this ),
url = "<?php echo get_template_directory_uri(); ?>/library/contact-form.php";
var posting = $.post( url, {
name: $('#name').val(),
email: $('#email').val(),
subject: $('#subject').val(),
message: $('#message').val(),
});
posting.done(function( data ) {
alert('success');
});
});
PHP:
// Set $to as the email you want to send the test to.
$to = "my#email.com";
// Email subject and body text.
$name = $_POST["name"];
$email = $_POST["email"];
$subject = $_POST["subject"];
$headers .= "Reply-To: ". strip_tags($_POST['email']) . "\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message = $_POST["message"];
// send test message using wp_mail function.
if(isset(($_POST['name']), ($_POST['email']), ($_POST['message']), ($_POST["subject"]))) {
$sent_message = wp_mail( $to, $subject, $message, $headers );
} else {
};
//display message based on the result.
if ( $sent_message ) {
// The message was sent.
echo 'The test message was sent. Check your email inbox.';
} else {
// The message was not sent.
echo 'The message was not sent!';
}
The code works when I run it on my local website, It returns the success alert.
The PHP code also succeeds in sending the contact form information to my email address.
I get a 'the server responded with a status of 500 (internal error)' when I run it on my web server.
I think I must have overlooked something stupid here but I can't see it and hoping someone else can see it and help me out?
Thanks in advance!
This is how i do my ajax submission for a form. It's contains WordPress security measures, you can learn them from google in detail but small description will be provided by me.
HTML
<form method="POST" id="contact-form">
<div class="contact-element flex-row">
<input class="" type="text" name="name" placeholder="Name" id="name" Required>
<input class="" type="text" name="email" placeholder="Email Address" id="email" Required>
</div>
<input class="" type="text" name="subject" placeholder="Subject" id="subject" Required>
<textarea type="text" name="message" rows="5" placeholder="Message" id="message" Required></textarea>
<input class="contact-submit" id="submit" name="submit" type="submit" value="Submit">
<input type="hidden" name="action" value="contact_form" id="cf_action" url="<?= admin_url('admin-ajax.php'); ?>">
<?php wp_nonce_field( 'contact_form', 'contact_form_wpnonce' ); ?>
</form>
Javascript
jQuery(function($){
$("#contact-form").submit(function(e){
var url = $('#cf_action').attr('url');
$.ajax({
type: "POST",
url: url,
data: $("#contact-form").serialize(),
success: function(data) {
alert(data.data);
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
});
Function
add_action('wp_ajax_contact_form', 'contact_form_function');
add_action('wp_ajax_nopriv_contact_form', 'contact_form_function');
function contact_form_function()
{
if ( !isset($_POST['xyz_contact_email_meta_box_nonce']) && !wp_verify_nonce($_POST['xyz_contact_email_meta_box_nonce'], 'xyz_save_contact_email_data')) {
# code...
return;
}
$user_name = sanitize_text_field( $_POST['name'] );
$user_email = sanitize_email( $_POST['email'] );
$user_subject = sanitize_text_field( $_POST['subject'] );
$user_message = sanitize_textarea_field( $_POST['message'] );
$to = 'xyz#gmail.com';
$subject = $user_subject;
$body = 'Hi you recived a message from '.$user_name.'('.$user_email.'),<p>'.$user_message.'</p>';
$headers = array('Content-Type: text/html; charset=UTF-8');
$status = wp_mail( $to, $subject, $body, $headers );
if($status){
wp_send_json_success('sent successful');
}else{
wp_send_json_error('something went wrong');
}
}
Description
okay let me guide through WordPress a bit.
WordPress have already inbuilt functionality to handle ajax-request from it's theme's functions.php, you have to copy and paste html code where you want form to show, js code in footer and function code in functions.php
Here are some tips:-
wp_nonce_field = it's used for security purpose and prevent hackers to use form for different purpose.
Sanitize data to make sure you are not receiving any malicious code from your posted data, you can use esc_attr(it will convert any tags and script into html) too.
It's a good habit to send data back with WordPress default function wp_send_json_success & wp_send_json_error.
(Forgive me if you feel hard to understand since it's my first answer on stackoverflow)
Cheers!!

Ajax/php contact form sending blank emails from time to time

Well I have this contact form that sends blank emails. But I did some testing and it doesn't happens to me. The only way this could happen, I think, would be by accesing the .php file directly. If not I don't know what could be the problem. The form doesn't let you send a blank email. If this keeps happening I'm going to add a validation in the php file too, but until I find out what is the problem I don't want to ignore this messages.
This is the HTML
<form name="contactForm" id="contactForm" method="post" action="/contactEngine.php" onsubmit="return validateForm()">
<input title="Input name" type="text" name="Name" id="Name" placeholder="Nombre:" required="">
<input title="Input email" placeholder="Email:" type="email" name="Email" id="Email" required="">
<input type="text" placeholder="Subject:" name="Subjet" id="Subjet">
<textarea title="Input message" placeholder="Mensaje:" name="Message" rows="20" cols="20" id="Message" required=""></textarea>
<input title="Input result" placeholder="25 + 25 = ?" type="text" name="Captcha" id="Captcha" required="">
<p id="wrongCaptcha"> Try again </p>
<input type="submit" name="submit" value="send" class="submit-button">
</form>
This is the JS
function validateForm(e) {
e.preventDefault();
var x = document.forms["contactForm"]["Captcha"].value;
if (x != 50) {//if captcha is wrong
$("#Captcha").addClass("wrongCaptchaEntered");
$("#Captcha").css("animation-name" , "none");
setTimeout (function(){
$("#Captcha").css("animation-name" , "changeBorder");
},100);
if ($("#wrongCaptcha").css("display") == "none"){
$("#wrongCaptcha").slideDown();
}
}
else { //if captcha is correct
var formAction = $("#contactForm").attr("action");
if (formAction == "/contactEngine.php"){
var formData = $("#contactForm").serialize();
$.post( formAction, formData, function(data){
console.log (data);
$(".formulario").changeTo({content: "<h2 class='section-title BackgroundGradientBlack'>"+ data +"</h2>"});
});
}
}
return false;
}
And the PHP
<?php
$EmailFrom = "EmailFrom#test.com";
$EmailTo = "EmailTo#test.com";
$Name = Trim(stripslashes($_POST['Name']));
$Email = Trim(stripslashes($_POST['Email']));
$Subject = Trim(stripslashes($_POST['Subjet']));
$Message = Trim(stripslashes($_POST['Message']));
$email_content = "Frontpage";
$email_content .= "\nNombre: $Name";
$email_content .= "\nEmail: $Email";
$email_content .= "\nMotivo: $Subject";
$email_content .= "\nMensaje: $Message";
$email_headers = "From: <$EmailFrom>";
if (mail($EmailTo, $Subject, $email_content, $email_headers)) {
http_response_code(200);
echo "Mensaje enviado";
} else {
http_response_code(500);
echo "Error";
}
?>
Thanks!
Probably some bot that's testing the PHP endpoint it can see in your JS and is sending data to it, trying to cause havoc. I bet if you logged the $_POST variable every time an email was sent, you'd seen a lot of spammy nonsense in some $_POST variables. Emails are blank just because the bots aren't smart enough to know which keys to use in its POSTs.

Form to different recipients based on radio button input

I cant think anymore, stuck trying to make this work. I've got two radio buttons, how do I send the form to one of two email adresses depending on the button clicked. I am a total idiot on php, thank you.
html
<div class="col-md-8 contact-top">
<h3>Book here Online!</h3>
<form method="post" action="FormtoEmail/FormtoEmail.php">
<form role="form">
<div class="form-group">
<label for="name">Name:</label>
<input type="name" class="form-control" id="name" placeholder="Name">
</div> <div class="form-group">
<label for="email">Email address:</label>
<input type="email" class="form-control" id="email" placeholder="Email">
</div>
<div class="form-group">
<label for="subject">Subject:</label>
<input type="subject" class="form-control" id="subject" placeholder="Subject">
</div>
<div class="radio">
<label><input type="radio" name="recipients" value="recipient_1">Booking Accommodation</label>
</div>
<div class="radio">
<label><input type="radio" name="recipients" value="recipient_2" >Booking Conference</label>
</div>
<div class="form-group">
<textarea rows="11" name="message" id="message" class="form-control" placeholder="Details"></textarea>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
my php
<?php
$my_email = "info#westcoastwebdesign.biz";
$continue = "/";
$errors = array();
// Remove $_COOKIE elements from $_REQUEST.
if(count($_COOKIE)){foreach(array_keys($_COOKIE) as $value){unset($_REQUEST[$value]);}}
// Check all fields for an email header.
function recursive_array_check_header($element_value)
{
global $set;
if(!is_array($element_value)){if(preg_match("/(%0A|%0D|\n+|\r+)(content-type:|to:|cc:|bcc:)/i",$element_value)){$set = 1;}}
else
{
foreach($element_value as $value){if($set){break;} recursive_array_check_header($value);}
}
}
recursive_array_check_header($_REQUEST);
if($set){$errors[] = "You cannot send an email header";}
unset($set);
// Validate email field.
if(isset($_REQUEST['email']) && !empty($_REQUEST['email']))
{
if(preg_match("/(%0A|%0D|\n+|\r+|:)/i",$_REQUEST['email'])){$errors[] = "Email address may not contain a new line or a colon";}
$_REQUEST['email'] = trim($_REQUEST['email']);
if(substr_count($_REQUEST['email'],"#") != 1 || stristr($_REQUEST['email']," ")){$errors[] = "Email address is invalid";}else{$exploded_email = explode("#",$_REQUEST['email']);if(empty($exploded_email[0]) || strlen($exploded_email[0]) > 64 || empty($exploded_email[1])){$errors[] = "Email address is invalid";}else{if(substr_count($exploded_email[1],".") == 0){$errors[] = "Email address is invalid";}else{$exploded_domain = explode(".",$exploded_email[1]);if(in_array("",$exploded_domain)){$errors[] = "Email address is invalid";}else{foreach($exploded_domain as $value){if(strlen($value) > 63 || !preg_match('/^[a-z0-9-]+$/i',$value)){$errors[] = "Email address is invalid"; break;}}}}}}
}
// Check referrer is from same site.
if(!(isset($_SERVER['HTTP_REFERER']) && !empty($_SERVER['HTTP_REFERER']) && stristr($_SERVER['HTTP_REFERER'],$_SERVER['HTTP_HOST']))){$errors[] = "You must enable referrer logging to use the form";}
// Check for a blank form.
function recursive_array_check_blank($element_value)
{
global $set;
if(!is_array($element_value)){if(!empty($element_value)){$set = 1;}}
else
{
foreach($element_value as $value){if($set){break;} recursive_array_check_blank($value);}
}
}
recursive_array_check_blank($_REQUEST);
if(!$set){$errors[] = "You cannot send a blank form";}
unset($set);
// Display any errors and exit if errors exist.
if(count($errors)){foreach($errors as $value){print "$value<br>";} exit;}
if(!defined("PHP_EOL")){define("PHP_EOL", strtoupper(substr(PHP_OS,0,3) == "WIN") ? "\r\n" : "\n");}
// Build message.
function build_message($request_input){if(!isset($message_output)){$message_output ="";}if(!is_array($request_input)){$message_output = $request_input;}else{foreach($request_input as $key => $value){if(!empty($value)){if(!is_numeric($key)){$message_output .= str_replace("_"," ",ucfirst($key)).": ".build_message($value).PHP_EOL.PHP_EOL;}else{$message_output .= build_message($value).", ";}}}}return rtrim($message_output,", ");}
$message = build_message($_REQUEST);
$message = $message . PHP_EOL.PHP_EOL."-- ".PHP_EOL."";
$message = stripslashes($message);
$subject = "Out of Africa Town Lodge Contact Form";
$headers = "From: " . $_POST['email'];
$recipients = array(
'recipient_1' => 'info#westcoastwebdesign.biz',
'recipient_2' => 'westcoastwebdesign77#gmail.com'
);
$my_email = $recipients[$_REQUEST['recipient']];
mail($my_email,$subject,$message,$headers);
?>
You need to use a radio button group with same name but value with different email id
<div class="radio">
<label><input type="radio" name="recipients" value="recipient_1#email.com">
Booking Accommodation
</label>
</div>
<div class="radio">
<label><input type="radio" name="recipients" value="recipient_2#email.com" >
Booking Conference
</label>
</div>
That way you can select one from two radio
in FormtoEmail.php
//use post to get the email id
$to = $_POST['recipients'];
and send mail using PHPMailer, its great library and will make your life easier
May you want use this code:
<?php
if(isset($_POST['recipients']) && $_POST['recipients'] == 'recipient_1') {
// send to recipient_1
} else {
// send to recipient_2
}
?>
$my_email = $recipients[$_REQUEST['recipient']];
There is a typo in $_REQUEST variable, it would be $recipients[$_REQUEST['recipients']];
Hope it will work now. It could be more easily done in anyway.

How to return to the previous page after a submit form with php?

I have a form in html whose "action" attribute calls a contact.php file. The problem is that after I submit the form, the file that is visible is a blank page with the address contact.php and I want to see again the form of the main page.
HTML:
<form id="myForm" action="php-contact/contact.php"
method="post" class="contact_form" autocomplete="off"
role="form">
<div class="form-group">
<label for="input-subject">subject</label>
<input name="subject" type="text" class="form-control" id="subject" placeholder="your subject" maxlength="20"/>
</div>
<div class="form-group">
<label for="input-name">name</label>
<input name="name" type="text" class="form-control" id="name" placeholder="your name" maxlength="20"/>
</div>
<div class="form-group">
<label for="input-email">email address</label>
<input name="email" type="text" class="form-control" id="email" placeholder="your email" maxlength="40"/>
</div>
<div class="form-group" >
<label for="input-message">message</label>
<textarea name="message" cols="10" rows="10" class="form-control" id="comment" ></textarea>
</div>
<button name="myFormSubmitted" type="submit" class="btn btn-primary btn-lg btn-block">send</button>
</form>
PHP:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$to = "pep.g#gmail.com";
$message = '
name: '.$name.'
email: '.$email.'
message: '.$message.'
';
$headers = 'From: pep.website#website.com';
if (
mail($to, $subject, $message, $headers)
)
echo"<script>alert('message send succesfully')</script>";
else
echo"<script>alert('message not send')</script>";
?>
Use either $_SERVER["HTTP_REFERER"] or use a hidden field on the form with the url of the current page:
<form action="myAction.php">
<input type="hidden" name="destination" value="<?php echo $_SERVER["REQUEST_URI"]; ?>"/>
<!-- other form inputs -->
<input type="submit"/>
</form>
myAction.php
<?php
/* Do work */
if(isset($_REQUEST["destination"])){
header("Location: {$_REQUEST["destination"]}");
}else if(isset($_SERVER["HTTP_REFERER"])){
header("Location: {$_SERVER["HTTP_REFERER"]}");
}else{
/* some fallback, maybe redirect to index.php */
}
And then even then you should have fallbacks in case for some reason the client isn't respecting HTTP redirects, like some redirect javascript, a meta redirect and a link to the destination.
Add a JS redirect after your alert then
echo "<script>
alert('message sent succesfully');
window.history.go(-1);
</script>";
In your contact.php file, just use something like at the end of the PHP code:
header("location:yourfilenamehere.php");
This will redirect back to whatever page you specify.
You could do two things...
1) Have your php logic in the form file and submit to that file. On the top of the file, put something like:
if(isset($_POST['name'])) {
// your sending logic
}
followed by your form.
2) use the header() function to redirect to your form.
header("Location: form.html");
I feel pretty bad about posting this answer as it is just concatenating two other SO answers.
First part
Charlie74's answer on this page
// add the message you want to show to the user
header("Location: yourfilenamehere.php?alertmsg=message+send+succesfully");
exit();
Second part check for the alertmsg name in the query string
See SO post for getParameterByName:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
in the page you are redirecting call the getParameterByName function:
<script>
var msg = getParameterByName('alertmsg');
if (alertmsg.length > 0) {
alert(msg);
}
</script>

Categories

Resources