I have designed the following slick Form and using it with PhP & ajax to submit ... its working fine including sending email to the targeted email ID .. There are total Seven (07) fields which suppose to be filled by the visitor. the problem is that when Someone submit the form with all fields I can only receive three (03) fields (Name, Email & Message).... the rest of the Four (04) fields (Phone,country,Budget & Select) are not showing in email... I am sure there must be some problem with my Php. Please tell me where I am mistaking in the following Php.
<?php
// Define some constants
define( "RECIPIENT_NAME", "John Smith" );
define( "RECIPIENT_EMAIL", "example#example.com" );
define( "EMAIL_SUBJECT", "Visitor Message" );
// Read the form values
$success = false;
$senderName = isset( $_POST['senderName'] ) ? preg_replace( "/[^\.\-\' a-zA-Z0-9]/", "", $_POST['senderName'] ) : "";
$senderEmail = isset( $_POST['senderEmail'] ) ? preg_replace( "/[^\.\-\_\#a-zA-Z0-9]/", "", $_POST['senderEmail'] ) : "";
$senderPhone = isset( $_POST['senderPhone'] ) ? preg_replace( "/[^\.\-\_\#a-zA-Z0-9]/", "", $_POST['senderPhone'] ) : "";
$senderCountry = isset( $_POST['senderCountry'] ) ? preg_replace( "/[^\.\-\_\#a-zA-Z0-9]/", "", $_POST['senderCountry'] ) : "";
$senderBudget = isset( $_POST['senderBudget'] ) ? preg_replace( "/[^\.\-\_\#a-zA-Z0-9]/", "", $_POST['senderBudget'] ) : "";
$senderSelect = isset( $_POST['senderSelect'] ) ? preg_replace( "/[^\.\-\_\#a-zA-Z0-9]/", "", $_POST['senderSelect'] ) : "";
$message = isset( $_POST['message'] ) ? preg_replace( "/(From:|To:|BCC:|CC:|Subject:|Content-Type:)/", "", $_POST['message'] ) : "";
// If all values exist, send the email
if ( $senderName && $senderEmail && $senderPhone && $senderCountry && $senderBudget && $senderSelect && $message ) {
$recipient = RECIPIENT_NAME . " <" . RECIPIENT_EMAIL . ">";
$headers = "From: " . $senderName . " <" . $senderEmail . ">";
$success = mail( $recipient, EMAIL_SUBJECT, $message, $headers );
}
// Return an appropriate response to the browser
if ( isset($_GET["ajax"]) ) {
echo $success ? "success" : "error";
} else {
?>
<html>
<head>
<title>Thanks!</title>
</head>
<body>
<?php if ( $success ) echo "<p>Thanks for sending your message! We'll get back to you shortly.</p>" ?>
<?php if ( !$success ) echo "<p>There was a problem sending your message. Please try again.</p>" ?>
<p>Click your browser's Back button to return to the page.</p>
</body>
</html>
<?php
}
?>
You have not added phone, country, budget and select fields while mailing. Try this:
if ( $senderName && $senderEmail && $senderPhone && $senderCountry && $senderBudget && $senderSelect && $message ) {
$msgToSend = "Name: ".$senderName."\r\n";
$msgToSend .= "Email: ".$senderEmail."\r\n";
$msgToSend .= "Phone: ".$senderPhone."\r\n";
$msgToSend .= "Sender Country: ".$senderCountry."\r\n";
$msgToSend .= "Sender Budget: ".$senderBudget."\r\n";
$msgToSend .= "Sender Select: ".$senderSelect."\r\n";
$msgToSend .= "Message: ".$message;
$recipient = RECIPIENT_NAME . " <" . RECIPIENT_EMAIL . ">";
$headers = "From: " . $senderName . " <" . $senderEmail . ">";
$success = mail( $recipient, EMAIL_SUBJECT, $msgToSend, $headers );
}
Related
Hi i have been trying for a good 2 hours to get this dropdown menu to get the selected result to go to email through post method im new to php and i think i could just do with abit of guidance ill post html php js code below.i have tried many ways this isnt my only edit ive literally tried everything i just need a little help
html
<div class="col-lg-3">
<div class="form-group mt-2">
<div class="dropdown" >
<select name="vehicles" id="vehicles" class="ddstyle">
<option value="motor" selected>Motorcycle</option>
<option value="Car">Car</option>
<option value="Small">Small Van</option>
<option value="Opel">Opel</option>
<option value="Midi">Midi Van</option>
<option value="SWB">SWB up to 2.4m</option>
<option value="MWB3">MWB up to 3m</option>
<option value="LWB4">LWB up to 4m</option>
<option value="XLWB4">XLWB 4m+</option>
<option value="Luton">Luton</option>
<option value="T5">7.5T</option>
</select>
</div>
</div>
</div>
PHP
<?php
if(!$_POST) exit;
// Email address verification, do not edit.
function isEmail($email) {
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$email));
}
if (!defined("PHP_EOL")) define("PHP_EOL", "\r\n");
$name = $_POST['name'];
$email = $_POST['email'];
$comments = $_POST['comments'];
$dod = $_POST['dod'];
$yourname = $_POST['yourname'];
$tel = $_POST['tel'];
$caddy = $_POST['caddy'];
$cpost = $_POST['cpost'];
$daddy = $_POST['daddy'];
$dpost = $_POST['dpost'];
$dofd = $_POST['dofd'];
$Car = $_POST['Car'];
$Small = $_POST['Small'];
$Opel = $_POST['Opel'];
$Midi = $_POST['Midi'];
$MWB = $_POST['MWB'];
$MWB3 = $_POST['MWB3'];
$LWB4 = $_POST['LWB4'];
$XLWB4 = $_POST['XLWB4'];
$Luton = $_POST['Luton'];
$T5 = $_POST['T5'];
//*$vehicles = $_POST['$vehicles'];**/
if(isset($_POST['send'])){
if(isset($_POST['vehicles'])){
$value = $_POST['vehicles'];
$ddme = $_POST['value'];
}
}
if(isset($_POST['vehicles']) && $_POST['vehicles']=='motor') echo $value;
if(trim($name) == '') {
echo '<div class="error_msg">You must enter your company name.</div>';
exit();
} else if(trim($email) == '') {
echo '<div class="error_msg">Please enter a valid email address.</div>';
exit();
} else if(!isEmail($email)) {
echo '<div class="error_msg">You have entered an invalid e-mail address. Please try again.</div>';
exit();
}
if(trim($dod) == '') {
echo '<div class="error_msg">Please enter your collection date.</div>';
exit();
}
if(trim($dofd) == '') {
echo '<div class="error_msg">Please enter your drop off deadline.</div>';
exit();
}
if(get_magic_quotes_gpc()) {
$comments = stripslashes($comments);
}
// Configuration option.
// Enter the email address that you want to emails to be sent to.
// Example $address = "joe.doe#yourdomain.com";
//$address = "example#example.net";
$address = "admin#ready2gologistics.co.uk";
// Configuration option.
// i.e. The standard subject will appear as, "You've been contacted by John Doe."
// Example, $e_subject = '$name . ' has contacted you via Your Website.';
$e_subject = ' ' . $name . ' has a possible job!';
// Configuration option.
// You can change this if you feel that you need to.
// Developers, you may wish to add more fields to the form, in which case you must be sure to add them here.
$e_body = "$name wants a quote details are listed below." . PHP_EOL . PHP_EOL;
$e_content =
"
Company: $name
Name of Person: $yourname
Contacts email: $email
Contacts Telephone Number: $tel
Desired Collection Date: $dod
Drop Off Deadline: $dofd
Collection Address: $caddy
Collection Post Code: $cpost
Destination Address: $daddy
Destination Post Code: $dpost
Addtional Information: $comments
test: $value
" . PHP_EOL . PHP_EOL;
$e_reply = "You can contact $name via email, $email";
$msg = wordwrap( $e_body . $e_content . $e_reply, 70 );
$headers = "From: $email" . PHP_EOL;
$headers .= "Reply-To: $email" . PHP_EOL;
$headers .= "MIME-Version: 1.0" . PHP_EOL;
$headers .= "Content-type: text/plain; charset=utf-8" . PHP_EOL;
$headers .= "Content-Transfer-Encoding: quoted-printable" . PHP_EOL;
if(mail($address, $e_subject, $msg, $headers)) {
// Email has sent successfully, echo a success page.
echo "<fieldset>";
echo "<div id='success_msg'>";
echo "<h3>Email Sent Successfully.</h3>";
echo "<p>Thank you <strong>$name</strong>, your quote has been submitted to us. To see how we use your information check out our <a href='PrivacyPolicy.html".$link_address."'>Privacy Policy</a></p>";
echo "</div>";
echo "</fieldset>";
} else {
echo 'ERROR!';
}
?>
JavaScript
//Contact
$('#working_form').submit(function() {
var action = $(this).attr('action');
$("#message").slideUp(750, function() {
$('#message').hide();
$('#submit')
.before('<img src="" class="gif_loader" />')
.attr('disabled', 'disabled');
$.post(action, {
name: $('#name').val(),
email: $('#email').val(),
comments: $('#comments').val(),
dod: $('#dod').val(),
dofd: $('#dofd').val(),
yourname: $('#yourname').val(),
cpost: $('#cpost').val(),
caddy: $('#caddy').val(),
tel: $('#tel').val(),
daddy: $('#daddy').val(),
dpost: $('#dpost').val(),
vehicles: $('#vehicles').val(),
value: $('#value').val(),
},
function(data) {
document.getElementById('message').innerHTML = data;
$('#message').slideDown('slow');
$('#cform img.gif_loader').fadeOut('slow', function() {
$(this).remove()
});
$('#submit').removeAttr('disabled');
if (data.match('success') != null) $('#cform').slideUp('slow');
}
);
});
return false;
});
In $.post request pass send value
$.post(action, {
...other data
value: $('#value').val(),
send: $('#send').val(),
}
Because your $value vehicle data is depended on if(isset($_POST['send'])) check
if(isset($_POST['send'])){
if(isset($_POST['vehicles'])){
$value = $_POST['vehicles'];
$ddme = $_POST['value'];
}
}
I want to redirect the user to another page only after displaying a success message. The code below redirects to the another page even if the page is refreshed without submitting any data.
Code Snippet
<?php
// We will store our status message later
$message = '';
// Let's check form submitted
if( isset( $_POST['action'] ) && $_POST['action'] == 'submit' ) {
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['number'];
$message_text = $_POST['address'];
if (isset($_POST['action']))
{
// Validate required fields
if( $name == '' || $email == '' || $message_text == '' ){
$message = "<p class=\"error\">Please fill out all required fields.</p>";
}
// send email after validation
else {
// Email will be sent at this email
$mailto = 'nepstarditsolutions#gmail.com';
// Let's create html email format
// (You can use html in this email format)
// Email headers
$headers = "From: " . strip_tags( $email ) . "\r\n";
$headers .= "Reply-To: ". strip_tags( $email ) . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
// Email body
$message = "<html><body>";
$message .= "<h3>Contact Info: </h3>";
$message .= "<p><strong>Name: </strong> ". strip_tags( $name ) . "</p>\r\n";
$message .= "<p><strong>Email: </strong> ". strip_tags( $email ) . "</p>\r\n";
$message .= "<p><strong>Contact Number: </strong> ". strip_tags( $phone ) . "</p>\r\n";
$message .= "<p><strong>Alternate Email: </strong> ". strip_tags( $_POST['altemail'] ) . "</p>\r\n";
$message .= "<p><strong>Hosting Package: </strong> ". strip_tags( $_POST['cradio'] ) . "</p>\r\n";
$message .= "<p><strong>Address: </strong>". strip_tags( $message_text ) . "</p>\r\n";
$message .= "</body></html>";
// Email subject
$subject = "Contact Info from ".$name;
// Send email
$mail_status = #mail( $mailto, $subject, $message, $headers );
if( $mail_status ){
$message = '<div class="alert alert-success">Quotation submitted Successfully ! </div>';
}
else {
$message = '<div class="alert alert-danger">Error in sending the Quotation ! </div>';
}
}
}
}
?>
I need help in 2 things
Success message should be displayed for 2 seconds (before the redirect).
How to redirect using JS in php?
Standard "vanilla" JavaScript way to redirect a page
You can use the code below to redirect the user after form submission code.
if( $mail_status ){
echo "
<script>
setTimeout(function() {
window.location = 'http://www.example.com/newlocation';
}, 2000);
</script>
";
}
MDN web docs on how setTimeout works
Hope it helps!
On a Linux server, I have an ajax form that gets posted to a js script, which in turn posts to a php routine for sending a web site email contact form (Styleshout-Puremedia template). I know the post is occurring to js, and to the php page. I get an httpd server error on the php page that "$Error is undefined". However if I define it as NULL or '' it exists and therefore doesn't pass the test "if (!$Error)". If I create a hard-coded php script using the mail function, the e-mail works so php and sendmail are all configured properly. Can someone help as to why this php script doesn't work, or how to fix the "$Error" error?
PHP code:
<?php
// Replace this with your own email address
$siteOwnersEmail = 'info#mydomain.com';
if($_POST) {
$fname = trim(stripslashes($_POST['contactFname']));
$lname = trim(stripslashes($_POST['contactLname']));
$email = trim(stripslashes($_POST['contactEmail']));
$subject = trim(stripslashes($_POST['contactSubject']));
$contact_message = trim(stripslashes($_POST['contactMessage']));
// Check First Name
if (strlen($fname) < 2) {
$error['fname'] = "Please enter your first name.";
}
// Check Last Name
if (strlen($lname) < 2) {
$error['lname'] = "Please enter your last name.";
}
// Check Email
if (!preg_match('/^[a-z0-9&\'\.\-_\+]+#[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is', $email)) {
$error['email'] = "Please enter a valid email address.";
}
// Check Message
if (strlen($contact_message) < 15) {
$error['message'] = "Please enter your message. It should have at least 15 characters.";
}
// Subject
if ($subject == '') { $subject = "Contact Form Submission"; }
// Set Name
$name = $fname . " " . $lname;
// Set Message
$message = "Email from: " . $name . "<br />";
$message .= "Email address: " . $email . "<br />";
$message .= "Message: <br />";
$message .= $contact_message;
$message .= "<br /> ----- <br /> This email was sent from your site's contact form. <br />";
// Set From: header
$from = $name . " <" . $email . ">";
// Email Headers
$headers = "From: " . $from . "\r\n";
$headers .= "Reply-To: ". $email . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
if (!$error) {
ini_set("sendmail_from", $siteOwnersEmail); // for windows server
$mail = mail($siteOwnersEmail, $subject, $message, $headers);
if ($mail) { echo "OK"; }
else { echo "Something went wrong. Please try again."; }
} # end if - no validation error
else {
$response = (isset($error['fname'])) ? $error['fname'] . "<br /> \n" : null;
$response .= (isset($error['lname'])) ? $error['lname'] . "<br /> \n" : null;
$response .= (isset($error['email'])) ? $error['email'] . "<br /> \n" : null;
$response .= (isset($error['message'])) ? $error['message'] . "<br />" : null;
echo $response;
} # end if - there was a validation error
}
?>
Thanks for your help!!
-Rob
You can always just initialize $error as
$error = [];
and then check for errors by
if(count($errors) === 0){
//no errors
}
Or, just use if(!isset($error)){//no errors}
I have PHP code that help me to other people can be in touch with me and send their opinion to me .
here's my PHP code :
<?php
$to = 'ticket.ritaweb#gmail.com';
$subject = 'Your decision/Opinion';
$name = htmlspecialchars($_REQUEST['name']);
$email = htmlspecialchars($_REQUEST['email']);
$site = htmlspecialchars($_REQUEST['site']);
$mobile = htmlspecialchars($_REQUEST['mobile']);
$nazar = htmlspecialchars($_REQUEST['nazar']);
$sqt = '2164854';
$sqtin = htmlspecialchars($_REQUEST['sqtin']);
if ($sqt === $sqtin) {
function clean_string($string) {
$bad = array("content-
type", "bcc:", "to:", "cc:", "href");
return str_replace($bad, "", $string);
}
$email_message .= "name : " . clean_string($name) . "\n";
$email_message .= "email : " . clean_string($email) . "\n";
$email_message .= "address : " . clean_string($site) . "\n";
$email_message .= "number : " . clean_string($mobile) . "\n";
$email_message .= "opinion : " . clean_string($nazar) . "\n";
$headers = 'From: ' . $mobile . "\r\n" . 'Reply-To: ' . $email . "\r\n" . 'X-Mailer:
PHP/' . phpversion();
mail($to, $subject, $email_message, $headers);
}
?>
and I called it with javascript ( ajax ) but I want a code in ajax that help me If my condition in PHP file was FALSE or each of the field was empty , show the message : "Your message was not send, be careful".
and here's my AJAX code :
<script type="text/javascript">
$(document).ready(function() {
$('#submit').click(function() {
$('#submit').attr('value', 'sending...');
$.post("themes/RitaWeb-v1/send.php", $(".rita_form").serialize(),
function(response) {
$('#submit').attr('value', 'sent.');
});
return false;
});
});
</script>
Use PHP to print messages on the page, like
{'status' : 'success'}
if the mail was sent and
{'status' : 'error'}
Then do something based on the output with js.
EDIT:
If you use jQuery.ajax instead of jQuery.post,you can also use the settings argument to let something happen if there ared errors during the request.
More information: http://api.jquery.com/jquery.ajax/
In your code, it would look like this.
PHP:
...
mail($to, $subject, $email_message, $headers);
print('{"status":"success"}');
}
else{
print('{"status":"error"}');
}
And your js:
$.ajax('themes/RitaWeb-v1/send.php').done(function(data){
status = $.parseJSON(data).status;
if(status == 'success'){
// do something
}
else if(ststus == 'error'){
// do something
}
else{
alert('unknown response');
}
});
Some help needed here, I'm building a one page wordpress theme and I don't really know how to make the contact form submit without loading. Basically all my code is on index.php.
This is the form submission php code above the get_header(); It works just fine but I can't really make it submit without loading the page.
if(isset($_POST['user_submit'])) {
$parse_uri = explode( 'wp-content', $_SERVER['SCRIPT_FILENAME'] );
require_once( $parse_uri[0] . 'wp-load.php' );
$name = esc_html($_POST['user_name']);
$email = esc_html($_POST['user_email']);
$comment = esc_html($_POST['user_message']);
$website = esc_html($_POST['user_url']);
$msg = esc_attr('Name: ', 'silver') . $name . PHP_EOL;
$msg .= esc_attr('E-mail: ', 'silver') . $email . PHP_EOL;
$msg .= esc_attr('Website: ', 'silver') . $website . PHP_EOL;
$msg .= esc_attr('Message: ', 'silver') . $comment;
$to = get_option( 'admin_email' );
$sitename = get_bloginfo('name');
$subject = '[' . $sitename . ']' . ' New Message';
$headers = 'From: ' . $name . ' <' . $email . '>' . PHP_EOL;
wp_mail($to, $subject, $msg, $headers);
}
This is the jQuery post I'm using for that:
$( "#contact_form" ).submit(function( event ) {
event.preventDefault();
var $form = $( this ),
name = $form.find( "input[name='user_name']" ).val(),
email = $form.find( "input[name='user_email']" ).val(),
website = $form.find( "input[name='user_url']" ).val(),
comment = $form.find( "input[name='user_message']").val();
$.post( templateDir + "/index.php", { website : website, comment : comment, name : name, email : email, submit : "yes" } );
});
This is the site http://silviuandrei.eu/themes/bornagain/
You're checking for the user_submit POST variable:
if(isset($_POST['user_submit']))
But sending a different variable via $.post
$.post( templateDir + "/index.php", { website : website, ..... submit : "yes" } );
Change it to user_submit : "yes"
I recommend doing it at functions.php using the init action:
add_action('init','form_submits');
function form_submits() {
if( isset($_REQUEST['user_submit']) ){
require("process_post.php");
exit;//prevents the default blog output
}
}
Note that using require is just a suggestion to keep functions.php clean.