This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 7 years ago.
I am picking up values and sending hidden field values through an AJAX call and then performing a query to update something in my database. The first initial query finds the id and other $_POST information and works great. However my email is not sending. My alert error message is not showing anything, but is displaying (it is a blank alert).
Does anyone see anything that is wrong with how am I am trying to send to my email or how I'm picking up the valuesin my email my email that it wouldn't send?
hidden input fields..
<input type="hidden" value="<?php echo $approved_id; ?>" id="approved_id" name="id" />
<input type="hidden" value="<?php echo $approved_firstname; ?>" id="approved_firstname" name="firstname" />
<input type="hidden" value="<?php echo $approved_lastname; ?>" id="approved_lastname" name="lastname" />
<input type="hidden" value="<?php echo $approved_username; ?>" id="approved_username" name="username" />
<input type="hidden" value="<?php echo $approved_email; ?>" id="approved_email" name="email" />
ajax call..
$(document).ready(function () {
$('#update_group').on('submit', function (event) {
event.preventDefault();
$.ajax({
url: 'user_group_update.php',
type: 'POST',
data: {
id: $("#approved_id").val(), //id
firstname: $("#approved_firstname").val(), //firstname
lastname: $("#approved_lastname").val(), //lastname
username: $("#approved_username").val(), //username
email: $("#approved_email").val(), //email
// update_group: $("#group_id").val() //group level
update_group: $(this).find( "#group_id option:selected" ).val()
},
success: function (data) {
//do something with the data that got returned
$(".group_success").fadeIn();
$(".group_success").show();
$('.group_success').html('User Permission Level Changed!');
$('.group_success').delay(5000).fadeOut(400);
alert(data);
},
error: function(jqXHR, textStatus,errorThrown )
{
// alert on an http error
alert( textStatus + errorThrown );
}
});
return false;
});
});
user_group_update.php
<?php
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . DIRECTORY_SEPARATOR . 'error.log');
error_reporting(E_ALL);
require_once 'core/init.php';
$approved_id = $_POST['id'];
//test - delete if it doesn't work
$approved_firstname = $_POST['firstname'];
$approved_lastname = $_POST['lastname'];
$approved_username = $_POST['username'];
$approved_email = $_POST['email'];
$change_group = $_POST['update_group'];
$con = mysqli_connect("localhost","","","");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = $con->prepare("UPDATE users,user_requests SET users.group=?, user_requests.group=? WHERE users.id=? AND user_requests.user_id=?");
if ( !$stmt || $con->error ) {
// Check Errors for prepare
die('User Group update prepare() failed: ' . htmlspecialchars($con->error));
}
if(!$stmt->bind_param('iiii', $change_group, $change_group, $approved_id, $approved_id)) {
// Check errors for binding parameters
die('User Group update bind_param() failed: ' . htmlspecialchars($stmt->error));
}
if(!$stmt->execute()) {
die('User Group update execute() failed: ' . htmlspecialchars($stmt->error));
}
//test
$email_stmt = $con->prepare("SELECT * FROM users WHERE id=?");
if ( !$email_stmt || $con->error ) {
// Check Errors for prepare
die('User email prepare() failed: ' . htmlspecialchars($con->error));
}
/*if(!$email_stmt->bind_param('ii', $change_group, $approved_id)) {
// Check errors for binding parameters
die('User email bind_param() failed: ' . htmlspecialchars($stmt->error));
}
if(!$email_stmt->execute()) {
die('User email execute() failed: ' . htmlspecialchars($stmt->error));*/
/*
$row = mysqli_fetch_assoc($$email_stmt);
$pending_id = $_POST['id'];
$group_firstname = $row['firstname'];
$group_lastname = $row['lastname'];
$group_username = $row['username'];
$group_email = $row['email'];
$group_email = $row['group'];*/
$to = $approved_email;
$subject = 'There is a new user request to join the Sunday Funday League';
$message = '
<html>
<head>
<title>New SFL User Request</title>
</head>
<body>
<p>Hi '.$approved_firstname.',</p><br>
<p>Your Sunday Funday League Account has been accepted. You have been added to the group. To sign in, click this link
http://sundayfundayleague.com . </p><br>
<p>Thank you,</p>
<p>Administration</p>
</body>
</html>
';
$from = "user-requests#sundayfundayleague.com";
$Bcc = "user-requests-confirm#sundayfundayleague.com";
// To send HTML mail, the Content-type header must be set
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Additional headers
//$headers .= 'To: ' .$to;//. "\r\n";
$headers .= 'From: ' .$from; "\r\n";
$headers .= 'Bcc: '.$Bcc; "\r\n";
// Send the email
mail($to,$subject,$message,$headers);
The mail() function in PHP will return true or false and you'll therefore not be able to see the error in the client.
You can however use error_get_last() when mail() fails as answered here.
Since the mail() function returns true or false you'll be able to create a simple if-statement to check if it was successful:
if(mail($to,$subject,$message,$headers)){
// success
} else {
print_r(error_get_last());
}
Try this to get more information about what's happening in the background.
Related
I want to make a contact form using php and javascript and I'm having a hard time with the alert() function. What I want to do, is inform the user of what's happening in the back end. I noticed that my "echo" functions get prompted into the console and I want to make them visible as an alert() function.
Here is my javascript:
$(document).ready(function() {
$("#submit").click(function() {
console.log("button clicked");
var name = $("#name").val();
var adresse = $("#adresse").val();
var telephone = $("#telephone").val();
var email = $("#email").val();
var project_place = $("#project_place").val();
var message = $("#message").val();
$("#returnmessage").empty(); // To empty previous error/success message.
// Checking for blank fields.
if (name == '' || email == '' || telephone == '' || message == '') {
alert("Please fill out the required fields.");
} else {
// Returns successful data submission message when the entered information is stored in database.
$.post("includes/mail.php", {
name1: name,
adresse1: adresse,
telephone1: telephone,
email1: email,
project_place1: project_place,
message1: message
}, function(data) {
console.log(data);
$("#returnmessage").append(data); // Append returned message to message paragraph.
if (data == "Email sent.") {
$("#frmContact")[0].reset(); // To reset form fields on success.
alert("Email sent.");
}
});
}
});
});
and here's my php:
<?php
// Fetching Values from URL.
$name = $_POST['name1'];
$adresse = $_POST['adresse1'];
$telephone = $_POST['telephone1'];
$email = $_POST['email1'];
$lieu_du_projet = $_POST['lieu_du_projet1'];
$message = $_POST['message1'];
$email = filter_var($email, FILTER_SANITIZE_EMAIL); // Sanitizing E-mail.
// After sanitization Validation is performed
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
if (!preg_match("/^[0-9]{10}$/", $telephone)) {
echo "Please, enter a valid number";
} else {
$subject = $name;
// To send HTML mail, the Content-type header must be set.
$headers = 'MIME-Version: 1.0' . "rn";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "rn";
$headers .= 'From:' . $email. "rn"; // Sender's Email
$headers .= 'Cc:' . $email. "rn"; // Carbon copy to Sender
$template = 'Hi ' . $nom . ","
. "\n\nThank you form contacting us,"
. "\nName: " . $name
. "\nAdresse: " . $adresse
. "\nTelephone: " . $telephone
. "\nEmail: " . $email
. "\nProject Place: " . $project_place
. "\nMessage: " . $message
. "\nThis is a confirmation email. "
. "\nWe'll get back to you as soon as possible";
$sendmessage = $template ;
// Message lines should not exceed 70 characters (PHP rule), so wrap it.
$sendmessage = wordwrap($sendmessage, 70);
// Send mail by PHP Mail Function.
mail("my#email.com", $subject, $sendmessage, $headers);
echo "Email sent.";
}
} else {
echo "Email invalid.";
}
?>
Any help would be appreciated, thanks a lot!
Sorry for the title gore I am a little over my head on this one and have tried everything I can find online. I'm trying to pass data via post to my sendjs.php file and I have an issue.
The ajax success function does not apply the if statement.
Live site here: www.diysoakwells.com.au (you can add an item and checkout to test).
I'm not even sure where to start to be honest so any information would be appreciated and I will update the post with any info as requested.
app.js
$(function() {
// Get the form.
var form = $("#ajax-contact");
// Get the messages div.
var formMessages = $("#form-messages");
var spinner = $("#spinner");
var submit = $("#submit");
// Set up an event listener for the contact form.
$(form).submit(function(e) {
// Stop the browser from submitting the form.
e.preventDefault();
//display the cog animation
$(spinner).removeClass("hidden");
//hide the submit button
$(submit).addClass("hidden");
jsonObj=[];
for(i=1;i<$(".item-price").length;i++)
{
var items={};
var itemname = $(".item-name").get(i);
var itemprice = $(".item-price").get(i);
var itemquantity = $(".item-quantity").get(i);
var itemtotal = $(".item-total").get(i);
items["name"] = itemname.innerHTML;
items["price"] = itemprice.innerHTML;
items["quantity"] = itemquantity.innerHTML;
items["total"] = itemtotal.innerHTML;
jsonObj.push(items);
}
console.log(items);
var formdata = {};
formdata["textbox"] = $("#textbox").val();
formdata["name"] = $("#name").val();
formdata["phone"] = $("#phone").val();
formdata["email"] = $("#email").val();
formdata["address"] = $("#address").val();
formdata["grandtotal"] = simpleCart.grandTotal();
var x =
{
"cart" : jsonObj,
"formdata" : formdata,
"captchaResponse" : $("#g-recaptcha-response").val()
};
//jsonString = jsonObj+formdata;
var y = JSON.stringify(x);
console.log(y);
var result = jQuery.parseJSON(y);
console.log(result);
// Serialize the form data.
//var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: "post",
url: "sendjs.php" ,
//url: $(form).attr("action"),
data: y,
contentType: "application/json; charset=utf-8",
traditional: true,
success: function (response) {
if(response=="Thank You! Your message has been sent.")
{
//remove the button animation
$(spinner).addClass("hidden");
$(formMessages).removeClass("error");
$(formMessages).addClass("success");
$("#textbox").val("");
$("#name").val("");
$("#email").val("");
$("#message").val("");
$("#phone").val("");
$("#address").val("");
}
else
{
$(formMessages).removeClass("success");
$(formMessages).addClass("error");
$(spinner).addClass("hidden");
$(submit).removeClass("hidden");
}
$(formMessages).text(response);
}
});
});
});
sendjs.php
<?php
//Debugging
//ini_set( 'display_errors', 1 );
//error_reporting( E_ALL );
//replaces file_get_contents due to restrictions on server
function get_data($url)
{
$ch = curl_init();
$timeout = 5;
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
//turn url_fopen on due to restrictions on server
//ini_set('allow_url_fopen', true);
date_default_timezone_set('Australia/Perth');
$time = date ("h:i A");
$date = date ("l, F jS, Y");
$json = file_get_contents('php://input');
$obj = json_decode($json,true);
$captcha = $obj["captchaResponse"];
$captcha;
$secretKey = "scrubbed";
$ip = $_SERVER['REMOTE_ADDR'];
$response = get_data("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha."&remoteip=".$ip);
//not used due to server restictions
//$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha."&remoteip=".$ip);
$responseKeys = json_decode($response,true);
if(intval($responseKeys["success"]) !== 1) {
echo "Please Click on the Captcha";
return false;
}
else
{
//echo $items;
$name = $obj["formdata"]["name"];
$phone = $obj["formdata"]["phone"];
$email = $obj["formdata"]["email"];
$textbox = $obj["formdata"]["textbox"];
$address = $obj["formdata"]["address"];
$grandtotal = $obj["formdata"]["grandtotal"];
$text = "<html style='font-family:arial'>
<body>
<h1 style='color:crimson;'>DIY Soakwells</h1>
<p>This order was submitted from www.diysoakwells.com.au on $date at $time</p>
<p>$name thank you for your order inquiry. Deliveries are normally every Friday, we will be in contact shortly to discuss your order and confirm a time.</p>
<p>An invoice will be issued after delivery for payment via bank transfer.</p>
<p>In the meantime if you haven't already seen it, you can take a look at www.soakwellcalculator.com.au to confirm the number of soakwells you ordered will be adequate.</p>
<br>
<h2 style='color:crimson;'>CUSTOMER DETAILS</h2>
<p><b>Email:</b>\n$email</p>
<p><b>Name:</b>\n$name</p>
<p><b>Phone:</b>\n$phone</p>
<p><b>Delivery Address:</b>\n$address</p>
<p><b>Message:</b>\n$textbox</p>
<br>
<h2 style='color:crimson;'>ORDER DETAILS</h2>";
$items_in_cart = count($obj["cart"]);
for($i=0; $i < $items_in_cart; $i++) {
$iname = $obj["cart"][$i]["name"];
$price = $obj["cart"][$i]["price"];
$quantity = $obj["cart"][$i]["quantity"];
$total = $obj["cart"][$i]["total"];
//display looped cart data
$items .= "<p>$iname x $quantity - $price <small>ea.</small> <b>Sub Total: </b> $total .</p>";
}
$final_total ="<br>
<p><b>Total: </b>$$grandtotal <small>inc. GST</small></p>
</body>
</html>";
//Email Content
$body = $text.$items.$final_total;
// Set the email subject.
$subject = "New order from $name";
// Build the email content.
$email_content = $body;
// Build the email headers.
$email_headers = 'MIME-Version: 1.0' . PHP_EOL;
$email_headers .= 'Content-Type: text/html; charset=ISO-8859-1' . PHP_EOL;
//$email_headers .= 'To:' . $name . '<' . $email . '>' . PHP_EOL;
$email_headers .= 'From: DIY Soakwells <orders#diysoakwells.com>' . PHP_EOL;
$email_headers .= 'CC: orders#diysoakwells.com.au' . PHP_EOL;
$email_headers .= 'Reply-To: DIY Soakwells <orders#diysoakwells.com.au>' . PHP_EOL;
$email_headers .= 'Return-Path: DIY Soakwells <orders#diysoakwells.com>' . PHP_EOL;
$email_headers .= 'X-Sender: DIY Soakwells <orders#diysoakwells.com.au' . PHP_EOL;
$email_headers .= 'X-Mailer: PHP/' . phpversion() . PHP_EOL;
//$email_headers .= 'X-Priority: 1' . PHP_EOL;
//validate Email
$email_check = filter_input(INPUT_POST, $email, FILTER_VALIDATE_EMAIL);
//Recipients
$to = $email;
if (mail($to, $subject, $email_content, $email_headers, '-forders#diysoakwells.com.au')) {
// Set a 200 (okay) response code.
//http_response_code(200);
echo "Thank You. Your order has been sent and a copy mailed to your inbox.";
} else {
// Set a 500 (internal server error) response code.
//http_response_code(500);
echo "There appears to be an issue with our server, please ring 0420 903 950 or email contact#diysoakwells.com.au.";
}
}
?>
Hope someone can give me some tips.
because your condition is response == "Thank You! Your message has been sent."
and your results are
"Please Click on the Captcha", "Thank You. Your order has been sent and a copy mailed to your inbox.", "There appears to be an issue with our server, please ring 0420 903 950 or email contact#diysoakwells.com.au.".
so all of your result will do else part
I've tried so many variables and been at this for hours and hours for something I know will be so simple haha, but I cannot get this to work... All I need to do, is... when the form is completed I have it redirected to a page instead of the normal error message.
Your help is appreciated.
<?php
//Retrieve form data.
//GET - user submitted data using AJAX
//POST - in case user does not support javascript, we'll use POST instead
$name = ($_GET['name']) ? $_GET['name'] : $_POST['name'];
$phone = ($_GET['phone']) ? $_GET['phone'] : $_POST['phone'];
$email = ($_GET['email']) ?$_GET['email'] : $_POST['email'];
$comment = ($_GET['comment']) ?$_GET['comment'] : $_POST['comment'];
//flag to indicate which method it uses. If POST set it to 1
if ($_POST) $post=1;
//Simple server side validation for POST data, of course, you should validate the email
if (!$name) $errors[count($errors)] = 'Please enter your name.';
if (!$phone) $errors[count($errors)] = 'Please enter your contact number.';
if (!$email) $errors[count($errors)] = 'Please enter your email.';
if (!$comment) $errors[count($errors)] = 'Please enter your comment.';
//if the errors array is empty, send the mail
if (!$errors) {
//recipient - replace your email here
$to = 'me#myemail.com';
//sender - from the form
$from = $name . ' <' . $email . '>';
//subject and the html message
$subject = 'Message from ' . $name;
$message = 'Name: ' . $name . '<br/><br/>
Phone: ' . $phone . '<br/><br/>
Email: ' . $email . '<br/><br/>
Message: ' . nl2br($comment) . '<br/>';
//send the mail
$result = sendmail($to, $subject, $message, $from);
//if POST was used, display the message straight away
if ($_POST) {
if ($result)
echo 'Thank you! We have received your message.';
else
echo 'Sorry, unexpected error. Please try again later';
//else if GET was used, return the boolean value so that
//ajax script can react accordingly
//1 means success, 0 means failed
} else {
echo $result;
}
//if the errors array has values
} else {
//display the errors message
for ($i=0; $i<count($errors); $i++) echo $errors[$i] . '<br/>';
echo 'Back';
exit;
}
//Simple mail function with HTML header
function sendmail($to, $subject, $message, $from) {
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= 'From: ' . $from . "\r\n";
$result = mail($to,$subject,$message,$headers);
if ($result)
return 1;
else
return 0;
}
I am trying to send an email from a form using php ,here is my PHP code(along with the validation ,didn't want to leave anything out :_)
<?php
/*
* Contact Form Class
*/
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
$admin_email = 'sgg3590#rit.edu'; // Your Email
$message_min_length = 5; // Min Message Length
class Contact_Form{
function __construct($details, $email_admin, $message_min_length){
$this->name = stripslashes($details['name']);
$this->email = trim($details['email']);
$this->subject = 'Contact from Your Website'; // Subject
$this->message = stripslashes($details['message']);
$this->email_admin = $email_admin;
$this->message_min_length = $message_min_length;
$this->response_status = 1;
$this->response_html = '';
}
private function validateEmail(){
$regex = '/^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i';
if($this->email == '') {
return false;
} else {
$string = preg_replace($regex, '', $this->email);
}
return empty($string) ? true : false;
}
private function validateFields(){
if(!$this->name)
{
$this->response_html .= '<p>Please enter your name</p>';
$this->response_status = 0;
}
// Check email
if(!$this->email)
{
$this->response_html .= '<p>Please enter an e-mail address</p>';
$this->response_status = 0;
}
// Check valid email
if($this->email && !$this->validateEmail())
{
$this->response_html .= '<p>Please enter a valid e-mail address</p>';
$this->response_status = 0;
}
// Check message length
if(!$this->message || strlen($this->message) < $this->message_min_length)
{
$this->response_html .= '<p>Please enter your message. It should have at least '.$this->message_min_length.' characters</p>';
$this->response_status = 0;
}
}
private function sendEmail(){
$mail = mail($this->email_admin, $this->subject, $this->message,
"From: ".$this->name." <".$this->email.">\r\n"
."Reply-To: ".$this->email."\r\n"
."X-Mailer: PHP/" . phpversion());
if($mail)
{
$this->response_status = 1;
$this->response_html = '<p>Thank You!</p>';
}
else
{
$this->response_status = 0;
$this->response_html = '<p>Sending failed</p>';
}
}
function sendRequest(){
$this->validateFields();
if($this->response_status)
{
$this->sendEmail();
}
$response = array();
$response['status'] = $this->response_status;
$response['html'] = $this->response_html;
echo json_encode($response);
}
}
$contact_form = new Contact_Form($_POST, $admin_email, $message_min_length);
$contact_form->sendRequest();
?>
here is how I am calling it
BRUSHED.contactForm = function(){
$("#contact-submit").on('click',function() {
$contact_form = $('#contact-form');
var fields = $contact_form.serialize();
$.ajax({
type: "POST",
url: "_include/php/contact.php",
data: fields,
dataType: 'json',
success: function(response) {
if(response.status){
$('#contact-form input').val('');
$('#contact-form textarea').val('');
}
$('#response').empty().html(response.html);
}
});
return false;
});
}
And here is my form
<form id="contact-form" class="contact-form" action="#">
<p class="contact-name">
<input id="contact_name" type="text" placeholder="Full Name" value="" name="name" />
</p>
<p class="contact-email">
<input id="contact_email" type="text" placeholder="Email Address" value="" name="email" />
</p>
<p class="contact-message">
<textarea id="contact_message" placeholder="Your Message" name="message" rows="5" cols="40"></textarea>
</p>
<p class="contact-submit">
<a id="contact-submit" class="submit" href="#">Send Your Email</a>
</p>
<div id="response">
</div>
</form>
The validations work proper so its going to the php file, but I can't send the email and the response div is not fill after I push the send button(neither with thank you or sending fail)
I followed this code from a website and I Don't really understand whats wrong here.. :(
First make sure you have set your machine host same as domain name, as sometimes mail-servers will deny mail-headers that doesn't have matching domain, like Sender: test#test.org but From: localhost.
Then, install postfix so it will correct any improper / incorrect stuff in the email and lastly, you're missing email headers there. Here are my example that works for me:
<?php
try {
$to = 'user#test.org';
$subject = 'Mail Test';
$message = <<<TEXT
Mail request received
TEXT;
$message = str_replace("\n.", "\n..", $message);
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: Test Org. <webmaster#test.org>' . "\r\n" .
'Reply-To: webmaster#test.org' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
printf("Mail sent to " + $to);
} catch (Exception $e) {
printf("Error occured: " + $e);
}
?>
If it still fails, you can try sending a test message from console echo "this is the body" | mail -s "test" "receipent#test.org" and see if it works. If both failed, best to ask server vendor as maybe they have set outgoing mail disabled or something.
Well I was using local host with WAMP and realized wamp server doesn't provide the functionality . THe code is good and working though.
Thanks
I am trying to pass $email field to thank you page which appears after redirection once user submits the enquiry form.
Its a 2 step enquiry form with thank you page being last.
It seems like the SESSION is live on thank you page however the values are lost. I'd like to get $email field posted on the thank you page to an iframe. Please let me know where exactly the session id is going wrong?
Here are the codes:
Step 1: Small Enquiry form
<?php
error_reporting(0);
session_start();
require_once('validation.class.php');
if(isset($_REQUEST['btnSubmit']) == 'Next'){
$obj = new validation();
$obj->add_fields(trim($_POST['txt_fname']), 'req', 'Enter your first name.');
$obj->add_fields(trim($_POST['txt_contact']), 'req', 'Enter phone number.');
$obj->add_fields(trim($_POST['txt_finamount']), 'req', 'Enter the amount.');
$obj->add_fields(trim($_POST['sel_loantype']), 'req', 'Please select vehicle type.');
$error = $obj->validate();
if($error){
$error_msg = "".$error."";
$_SESSION['error_msgs'] = $error_msg;
header("location:".$_SERVER['HTTP_REFERER']."");
exit();
}else{
$_SESSION['form1data'] = $_REQUEST;
header("location: quick-quote.php");
exit();
/*$fname = trim($_REQUEST["txt_fname"]);
$surname = trim($_REQUEST["txt_surname"]);
$phone = trim($_REQUEST["txt_contact"]);
$finamount = trim($_REQUEST['txt_finamount']);
$sel_loantype = trim($_REQUEST['sel_loantype']);
$message = '<html><body>';
$message .= '<table rules="all" width="100%" style="border:1px solid #666;" cellpadding="10">';
$message .= "<tr><td><strong>First Name:</strong> </td><td>" . strip_tags($fname) . "</td></tr>";
if($surname != ''){
$message .= "<tr><td><strong>Surname:</strong> </td><td>" . strip_tags($surname) . "</td></tr>";
}
$message .= "<tr><td><strong>Phone:</strong> </td><td>" . strip_tags($phone) . "</td></tr>";
$message .= "<tr><td><strong>Amount to Finance:</strong> </td><td>" . strip_tags($finamount) . "</td></tr>";
$message .= "<tr><td><strong>Loan Type:</strong> </td><td>" . strip_tags($sel_loantype) . "</td></tr>";
$message .= "</table>";
$message .= "</body></html>";
$ToEmail = 'testemail#gmail.com';
$EmailSubject = "GET A QUICK QUOTE from ".strip_tags($fname);
$mailheader = "From: ".strip_tags($fname)."\r\n";
//$mailheader .= "Reply-To: ".$_REQUEST["txt_email"]."\r\n";
$mailheader .= "Content-type: text/html; charset=iso-8859-1\r\n";
$MESSAGE_BODY = $message;
if(#mail($ToEmail, $EmailSubject, $MESSAGE_BODY, $mailheader)){
$_SESSION['sucess'] = "Your message has been sent successfully.";
$_SESSION['form1data'] = $_REQUEST;
header("location: quick-quote.php");
exit;
}else{
$_SESSION['sucess'] = "Sorry! Your message has not been sent.";
$_SESSION['form1data'] = $_REQUEST;
header("location: quick-quote.php");
exit;
}*/
}
}
?>
Step 2 Code:
<?php
error_reporting(0);
session_start();
require_once('validation.class.php');
?>
<script type="text/javascript">
function submitToCRM()
{
$.ajax({
type: 'POST',
url: 'http://test.com.au/quick-quote/car-finance/quickquote-one.php',
data: $("#applynowform").serialize(),
beforeSend: function () {
$("#loadingimg").show();
},
success: function (){
//alert(data);
window.location.href = "http://www.test.com.au/thank-you";
}
});
Step 3: The above page sends data to quickquote-one.php form processing script which has below code.
<?php
if(!isset($_SESSION))
{
session_start();
}
$_SESSION['user_email'] = $_POST['email'];
Step 4: thank you page (this page has below code)
<?php
if(!isset($_SESSION))
{
session_start();
$_SESSION['user_email'] = $_POST['email'];
echo $_SESSION['user_email'];
}
?>
Add
session_set_cookie_params(0);
before your
session_start();
You can also pass the SID (session ID) between the pages using the URL to make sure it isn't lost in transition.
url: 'http://test.com.au/quick-quote/car-finance/quickquote-one.php?<?php echo htmlspecialchars(SID); ?>',
and
window.location.href = "http://www.test.com.au/thank-you?<?php echo htmlspecialchars(SID); ?>";
You're losing the session because you're sending the browser to the next URL without a relative path but instead a fully-qualified domain. This is a security measure to prevent session IDs from being inadvertently sent to the wrong server.
Another small solution would be to use relative paths like /page.php instead of http://www.domain.com/page.php
Read more here (PHP Manual)
In step 4 your setting
$_SESSION['user_email']
again. If the form has refreshed then your post is empty and you are overwriting the session with an empty value. Try removing it from step 4 and just leave.
<?php
if(isset($_SESSION['user_email']) && !empty($_SESSION['user_email']))
{
echo $_SESSION['user_email'];
}
?>
Also you are trying to echo your session email value IF the session is NOT set. I don't think that will work if the session is actually set..
i think it is better to start a session in one page and access all the session variables throghout if all the pages are connected to eachother. it will be some thing like we create login page. When user logs in capture alll the required values in a session and can be accessed through out the application even after refresh.
$query = "SELECT Useid,UserName,AccountStatus, FullName FROM Users WHERE UserName = :UserName";
from this query we can get the session variables easily.
if($login_ok)
{
//for last visit
$Month = 2592000 + time();
//this adds 30 days to the current time
setcookie(AboutVisit, date("F jS - g:i a"), $Month);
//last visit ends here.
$_SESSION['user'] = $row['UserName'];
$_SESSION['userid'] = $row['Useid'];
$_SESSION['fullname'] = $row['FullName'];
}
where ever you need th variable you can use like this
$username=$_SESION['user'];
I think this will work instead of startign session every time in each page.
Hope it helps