PHPMailer: Send e-mail from form - html-email

I would like to implement sending email function where I want to allow admin of the system I developed to be able to send email from HTML form to the desired members.
I have searched here and tried all the possible solutions but still could not make it work. I didn't receive the email and SMTPDebug didn't tell me anything. I also have turned off Gmail's less secure apps.
Can someone please point it out for me why it doesn't work?
This is my form:
<form name="compose" method="POST" action="sendmail.php">
<table>
<tr>
<thead>Compose New Message</thead>
</tr>
<tr>
<td>To</td>
<td>:</td>
<td>
<input type="text" id="to" size="57">
</td>
</tr>
<tr>
<td>Subject</td>
<td>:</td>
<td>
<input type="text" id="subject" size="57">
</td>
</tr>
<tr>
<td></td>
<td></td>
<td>
<textarea cols="39" rows="10" id="content"></textarea>
</td>
</tr>
<tr>
<td></td>
<td></td>
<td>
<input type="submit" id="submit" value="Send Message">
</td>
</tr>
</table>
</form>
And this is my sendmail.php :
<?php
require 'includes/PHPMailer/PHPMailerAutoload.php';
require 'includes/PHPMailer/class.smtp.php';
if(isset($_POST['submit']))
{
$recipient = $_POST['to'];
$subject = $_POST['subject'];
$body = $_POST['content'];
$mail = new PHPMailer;
$mail->isSMTP();
//smtp debugging
$mail->SMTPDebug = 2;
$mail->DebugOutput = 'html';
$mail->Host = 'smtp.gmail.com';
$mail->Host = gethostbyname('smtp.gmail.com');
$mail->Port = 587;
$mail->SMTPAuth = true;
$mail->SMTPKeepAlive = true;
$mail->SMTPSecure = 'tls';
$mail->Username = "myemail";
$mail->Password = "mypassword";
$mail->setFrom('myemail', 'Azie');
$mail->AddAddress = $recipient;
$mail->Subject = $subject;
$mail->Body = $body;
//send the message, check for errors
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
}
?>

Related

Flutter Webview Form Post

Below is code in PHP for PayU Payment gateway integration. Payment Gateway is opened via a Post form submit and form action is url https://sandboxsecure.payu.in
Using Webview we can redirect to https://sandboxsecure.payu.in. but need to send the data as well.
Can we create similar flow in flutter web?
Possible flow
Flutter Web --- > Submit form and open webview to show PayU Page --> After payment come back to flutter web
note - Hash generation will be done via third party API.
<?php
$MERCHANT_KEY = "";
$SALT = "";
// Merchant Key and Salt as provided by Payu.
$PAYU_BASE_URL = "https://sandboxsecure.payu.in"; // For Sandbox Mode
//$PAYU_BASE_URL = "https://secure.payu.in"; // For Production Mode
$action = '';
$posted = array();
if(!empty($_POST)) {
//print_r($_POST);
foreach($_POST as $key => $value) {
$posted[$key] = $value;
}
}
$formError = 0;
if(empty($posted['txnid'])) {
// Generate random transaction id
$txnid = substr(hash('sha256', mt_rand() . microtime()), 0, 20);
} else {
$txnid = $posted['txnid'];
}
$hash = '';
// Hash Sequence
$hashSequence = "key|txnid|amount|productinfo|firstname|email|udf1|udf2|udf3|udf4|udf5|udf6|udf7|udf8|udf9|udf10";
if(empty($posted['hash']) && sizeof($posted) > 0) {
if(
empty($posted['key'])
|| empty($posted['txnid'])
|| empty($posted['amount'])
|| empty($posted['firstname'])
|| empty($posted['email'])
|| empty($posted['phone'])
|| empty($posted['productinfo'])
|| empty($posted['surl'])
|| empty($posted['furl'])
|| empty($posted['service_provider'])
) {
$formError = 1;
} else {
//$posted['productinfo'] = json_encode(json_decode('[{"name":"tutionfee","description":"","value":"500","isRequired":"false"},{"name":"developmentfee","description":"monthly tution fee","value":"1500","isRequired":"false"}]'));
$hashVarsSeq = explode('|', $hashSequence);
$hash_string = '';
foreach($hashVarsSeq as $hash_var) {
$hash_string .= isset($posted[$hash_var]) ? $posted[$hash_var] : '';
$hash_string .= '|';
}
$hash_string .= $SALT;
$hash = strtolower(hash('sha512', $hash_string));
$action = $PAYU_BASE_URL . '/_payment';
}
} elseif(!empty($posted['hash'])) {
$hash = $posted['hash'];
$action = $PAYU_BASE_URL . '/_payment';
}
?>
<html>
<head>
<script>
var hash = '<?php echo $hash ?>';
function submitPayuForm() {
if(hash == '') {
return;
}
var payuForm = document.forms.payuForm;
payuForm.submit();
}
</script>
</head>
<body onload="submitPayuForm()">
<h2>PayU Form</h2>
<br/>
<?php if($formError) { ?>
<span style="color:red">Please fill all mandatory fields.</span>
<br/>
<br/>
<?php } ?>
<form action="<?php echo $action; ?>" method="post" name="payuForm">
<input type="hidden" name="key" value="<?php echo $MERCHANT_KEY ?>" />
<input type="hidden" name="hash" value="<?php echo $hash ?>"/>
<input type="hidden" name="txnid" value="<?php echo $txnid ?>" />
<table>
<tr>
<td><b>Mandatory Parameters</b></td>
</tr>
<tr>
<td>Amount: </td>
<td><input name="amount" value="<?php echo (empty($posted['amount'])) ? '' : $posted['amount'] ?>" /></td>
<td>First Name: </td>
<td><input name="firstname" id="firstname" value="<?php echo (empty($posted['firstname'])) ? '' : $posted['firstname']; ?>" /></td>
</tr>
<tr>
<td>Email: </td>
<td><input name="email" id="email" value="<?php echo (empty($posted['email'])) ? '' : $posted['email']; ?>" /></td>
<td>Phone: </td>
<td><input name="phone" value="<?php echo (empty($posted['phone'])) ? '' : $posted['phone']; ?>" /></td>
</tr>
<tr>
<td>Product Info: </td>
<td colspan="3"><textarea name="productinfo"><?php echo (empty($posted['productinfo'])) ? '' : $posted['productinfo'] ?></textarea></td>
</tr>
<tr>
<td>Success URI: </td>
<td colspan="3"><input name="surl" value="<?php echo (empty($posted['surl'])) ? '' : $posted['surl'] ?>" size="64" /></td>
</tr>
<tr>
<td>Failure URI: </td>
<td colspan="3"><input name="furl" value="<?php echo (empty($posted['furl'])) ? '' : $posted['furl'] ?>" size="64" /></td>
</tr>
<tr>
<td colspan="3"><input type="hidden" name="service_provider" value="payu_paisa" size="64" /></td>
</tr>
<tr>
<td><b>Optional Parameters</b></td>
</tr>
<tr>
<td>Last Name: </td>
<td><input name="lastname" id="lastname" value="<?php echo (empty($posted['lastname'])) ? '' : $posted['lastname']; ?>" /></td>
<td>Cancel URI: </td>
<td><input name="curl" value="" /></td>
</tr>
<tr>
<td>Address1: </td>
<td><input name="address1" value="<?php echo (empty($posted['address1'])) ? '' : $posted['address1']; ?>" /></td>
<td>Address2: </td>
<td><input name="address2" value="<?php echo (empty($posted['address2'])) ? '' : $posted['address2']; ?>" /></td>
</tr>
<tr>
<td>City: </td>
<td><input name="city" value="<?php echo (empty($posted['city'])) ? '' : $posted['city']; ?>" /></td>
<td>State: </td>
<td><input name="state" value="<?php echo (empty($posted['state'])) ? '' : $posted['state']; ?>" /></td>
</tr>
<tr>
<td>Country: </td>
<td><input name="country" value="<?php echo (empty($posted['country'])) ? '' : $posted['country']; ?>" /></td>
<td>Zipcode: </td>
<td><input name="zipcode" value="<?php echo (empty($posted['zipcode'])) ? '' : $posted['zipcode']; ?>" /></td>
</tr>
<tr>
<td>UDF1: </td>
<td><input name="udf1" value="<?php echo (empty($posted['udf1'])) ? '' : $posted['udf1']; ?>" /></td>
<td>UDF2: </td>
<td><input name="udf2" value="<?php echo (empty($posted['udf2'])) ? '' : $posted['udf2']; ?>" /></td>
</tr>
<tr>
<td>UDF3: </td>
<td><input name="udf3" value="<?php echo (empty($posted['udf3'])) ? '' : $posted['udf3']; ?>" /></td>
<td>UDF4: </td>
<td><input name="udf4" value="<?php echo (empty($posted['udf4'])) ? '' : $posted['udf4']; ?>" /></td>
</tr>
<tr>
<td>UDF5: </td>
<td><input name="udf5" value="<?php echo (empty($posted['udf5'])) ? '' : $posted['udf5']; ?>" /></td>
<td>PG: </td>
<td><input name="pg" value="<?php echo (empty($posted['pg'])) ? '' : $posted['pg']; ?>" /></td>
</tr>
<tr>
<?php if(!$hash) { ?>
<td colspan="4"><input type="submit" value="Submit" /></td>
<?php } ?>
</tr>
</table>
</form>
</body>
</html>
You can use the below package:
https://pub.dev/packages/flutter_inappwebview
InAppWebView(
initialUrlRequest: URLRequest(
url: Uri.parse(targetUrl),
method: 'POST',
body: Uint8List.fromList(utf8.encode("msg=${requestPayload}")),
headers: {
'Content-Type': 'multipart/form-data',
'Referer': ,
'access_token': _,
'Host':'esign.egov-nsdl.com',
'Content-Length': Uint8List.fromList(utf8.encode("msg=${requestPayload}")).length.toString(),
}
),
onWebViewCreated: (controller) {
},
),
This should work with the required modifications..

show the "add another" button when the form is successfully send using codeigniter

i have this form called news and events, I want that when the form is successfully saved, the table form will hide then the add another button will appear. Im using session set userdata so that when the form is successfully saved the add another button will appear then the table form will hide. my code runs well but the problem is, after it successfully send the add another button will not work here's my controller below
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
session_start();
class News_and_events extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->library('form_validation');
$this->load->model('admin_model', 'am');
}
public function index(){
if($this->session->userdata('logged_in')){
$this->data['title'] = 'News and Events | Spring Rain Global Consultancy Inc Admin Panel';
$this->data['logout'] = 'Logout';
$session_data = $this->session->userdata('logged_in');
$this->data['id'] = $session_data['id'];
$this->data['username'] = $session_data['username'];
$this->data['allData'] = $this->am->getAllData();
$this->load->view('pages/admin_header', $this->data);
$this->load->view('content/news_and_events', $this->data);
$this->load->view('pages/admin_footer');
}else{
redirect('login', 'refresh');
}
}
public function add(){
if($this->session->userdata('logged_in')){
$this->form_validation->set_rules('date', 'Date', 'trim|required|xss_clean');
$this->form_validation->set_rules('event', 'Event', 'trim|required|xss_clean');
$this->form_validation->set_rules('description', 'Description', 'trim|required|xss_clean');
if($this->form_validation->run() == FALSE){
$this->data['title'] = 'News and Events | Spring Rain Global Consultancy Inc Admin Panel';
$this->data['logout'] = 'Logout';
$session_data = $this->session->userdata('logged_in');
$this->data['id'] = $session_data['id'];
$this->data['username'] = $session_data['username'];
$this->data['allData'] = $this->am->getAllData();
$this->load->view('pages/admin_header', $this->data);
$this->load->view('content/news_and_events', $this->data);
$this->load->view('pages/admin_footer');
}else{
$array = array(
'Date' => $this->input->post('date'),
'Event' => $this->input->post('event'),
'Description' => $this->input->post('description')
);
$this->am->saveData($array);
$this->session->set_userdata('add_another', $array);
redirect('news_and_events', 'refresh');
}
}else{
redirect('homepage', 'refresh');
}
}
}
and my views
<div class="container" >
<br />
<br />
<br />
<ul id="nav">
<li><h4>Home</h4></li>
<li><h4>News and Events</h4></li>
<li><h4>Activities</h4></li>
</ul>
<div class="starter-template">
<h1>News And Events</h1>
<?php if($this->session->set_userdata('add_another')):?>
<div id="add_another" style="float:left;">
<input type="button" value="Add Another" class="btn btn-primary" />
</div>
<?php else: ?>
<form action="<?php echo base_url().'news-and-events/add'?>" method="post">
<?php echo validation_errors('<div class="error">', '</div>');?>
<table class="table-striped">
<tr>
<td>Date: </td>
<td><input type="text" id="datepicker" name="date" value="<?php echo set_value('date');?>" /></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td >Event: </td>
<td ><input type="text" name="event" value="<?php echo set_value('event');?>" /></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td width="20%">Description: </td>
<td><textarea cols="30" rows="5" name="description" ><?php echo set_value('description');?></textarea></td>
</tr>
<tr>
<td width="20%"> </td>
<td><input type="submit" value="Add" class="btn btn-success" /></td>
</tr>
</table>
</form>
<?php endif; ?>
<br />
<br />
<table class="table" >
<tr>
<th>Date</th>
<th width="51%">Event</th>
<th>Description</th>
<th>Options</th>
</tr>
<?php foreach($allData as $allData): ?>
<tr>
<td><?php echo $allData->Date; ?></td>
<td><?php echo $allData->Event; ?></td>
<td></td>
<td></td>
</tr>
<?php endforeach; ?>
</table>
</div>
</div><!-- /.container -->
<script>
var date = new Date();
var currentMonth = date.getMonth();
var currentDate = date.getDate();
var currentYear = date.getFullYear();
$('#datepicker').datepicker({
minDate: new Date(currentYear, currentMonth, currentDate),
dateFormat: "yy-mm-dd"
});
</script>
in my views file ive added there the if else statement $this->session->set_userdata('add') just below the h1 tag which is news and events this will trigger the statement when the form is successfully saved!
can someone help me figured this out? or how to do this correctly?
any help is much appreciated! thanks!
istead of this line
<?php if($this->session->set_userdata('add_another')):?>
use this
<?php if($this->session->userdata('add_another')):?>
and in your controller before loading the view add this line
$this->session->set_userdata('add_another',1);

Contact form cannot work well on specific email

I am facing a problem for my form.
It cannot receive well when i set abc#xxxx.co.id as receiver. All message is correct, just it will stat with "Content-type: text/html; charset=utf-8 " and come with table format.
It should look tidy.
Content-type: text/html; charset=utf-8
To: crm#merekmu.co.id
From: <hl.tam#webnic.cc>
Message-Id: <20130618031715.7DA4712406D9#gemilang-pandi.localdomain>
Date: Tue, 18 Jun 2013 10:17:15 +0700 (WIT)
<html>
<head>
<title>Merekmu “LIKE and WIN” Contest Submission</title>
</head>
<body>
<h2>Merekmu “LIKE and WIN” Contest Submission</h2>
<table width='95%' cellpadding='0' cellspacing='11'>
However, this form work well if i use another email as receiver(123#xxxx.com). Use same code, i just change email.
I made some testing as below:
email 1:abc#xxxx.co.id
email 2:123#xxxx.com
web 1:www.456.com
web 2:www.abc.co.id
Test 1: set email abc#xxxx.co.id as receiver at www.abc.co.id - messy message receive
Test 2: set email 123#xxxx.com as receiber at www.abc.co.id - work well and show tidy message
Test 3: set email abc#xxxx.co.id as receiver at www.456.com - work well and show tidy message
I have no idea with what problem is it?
<?php
$firstName= $_POST['firstName'];
$lastName= $_POST['lastName'];
$email= $_POST['email'];
$fbUrl= $_POST['fbUrl'];
$blog= $_POST['blog'];
// subject
$subject = $name;
// message
$message = "
<html>
<head>
<title>Merekmu “LIKE and WIN” Contest Submission</title>
</head>
<body>
<h2>Merekmu “LIKE and WIN” Contest Submission</h2>
<table width='95%' cellpadding='0' cellspacing='11'>
<tr>
<td width='189'> First Name:</td>
<td>$firstName</td>
</tr>
<tr>
<td width='189'> Last Name:</td>
<td>$lastName</td>
</tr>
<tr>
<td width='189'> Email:</td>
<td>$email</td>
</tr>
<tr>
<td width='189'> Facebook profile URL:</td>
<td>$fbUrl</td>
</tr>
<tr>
<td width='189'> Blog:</td>
<td>$blog</td>
</tr>
</tr>
</table>
</body>
</html>
";
// To send HTML mail, the Content-type header must be set
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
// Additional headers
$headers .= "To:crm#merekmu.co.id" . "\r\n";
$headers .= "From:".$name."<".$email.">\r\n";
$subject .= "Merekmu “LIKE and WIN” Contest Submission ";
//$headers .= 'Cc: birthdayarchive#example.com' . "\r\n";
//$headers .= 'Bcc: birthdaycheck#example.com' . "\r\n";
if(mail($toemail, $subject, $message, $headers)) {
echo '';
} else {
echo '';
}
?>
valindation
$(document).ready(function() {
$('form#contactForm').submit(function() {
$('form#contactForm .error').remove();
var hasError = false;
$('.requiredField').each(function() {
if(jQuery.trim($(this).val()) == '') {
var labelText = $(this).prev('label').text();
$(this).parent().append('<div class="error">Lapangan tidak boleh kosong.</div>');
hasError = true;
} else if($(this).hasClass('email')) {
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if(!emailReg.test(jQuery.trim($(this).val()))) {
var labelText = $(this).prev('label').text();
$(this).parent().append('<div class="error">Silakan masukkan email yang valid.</div>');
hasError = true;
}
}
});
if(!hasError) {
$('form#contactForm li.submit_btn').fadeOut('normal', function() {
$(this).parent().append('<img src="/wp-content/themes/td-v3/images/template/loading.gif" alt="Loading…" height="31" width="31" />');
});
var formInput = $(this).serialize();
$.post($(this).attr('action'),formInput, function(data){
$('form#contactForm').slideUp("fast", function() {
$(this).before('<p class="thanks">Formulir telah dikirimkan.</p>');
});
});
}
return false;
});
});
HTML
<form action="submit.php" id="contactForm" method="post">
<table border="0" cellspacing="0" cellpadding="0">
<tr>
<td valign="top" colspan="2" align="center"> <div class="title"> Merekmu “LIKE and WIN” Contest Submission </div></td>
</tr>
<tr>
<td valign="top" width="200" class="form-left"><label for="contactName"><strong>First Name:</strong> <span class="require">*</span></label></td>
<td valign="top">
<input type="text" name="firstName" id="firstName" value="" class="requiredField" /></td>
</tr>
<tr>
<td valign="top" class="form-left"><label for="contactName"><strong>Last Name:</strong> <span class="require">*</span></label></td>
<td valign="top">
<input type="text" name="lastName" id="lastName" value="" class="requiredField" /></td>
</tr>
<tr>
<td valign="top" class="form-left"><label for="email"><strong>Email:</strong> <span class="require">*</span></label></td>
<td valign="top">
<input type="text" name="email" id="email" value="" class="requiredField email" /></td>
</tr>
<tr>
<td valign="top" class="form-left"><label for="tel"><strong>Facebook profile URL:</strong> <span class="require">*</span></label>
</td>
<td valign="top">
<input type="text" name="fbUrl" id="fbUrl" value="" class="requiredField" /></td>
</tr>
<tr>
<td valign="top" class="form-left"><label for="tel"><strong>Blog:</strong> </label>
</td>
<td valign="top">
<input type="text" name="blog" id="blog" value="" /></td>
</tr>
<tr>
<td valign="top" colspan="2" align="center"> <input class="submit_btn" type="submit" value="Submit" />
</td>
</tr>
</table>
</form>

post value still retains the same value after assigning it using $.post

<script type="text/javascript">
$(document).ready(function($) {
$('#searchicon').click(function(){
$('#searchicon.toappear').toggle();
$('#searchicon2.appear').toggle();
$('#extraSearch').slideToggle('fast');
});
$('#searchicon2').click(function(){
$('#searchicon.toappear').toggle();
$('#searchicon2.appear').toggle();
$('#extraSearch').slideToggle('fast');
});
$('input[name=estimate]').click(function(){
if (this.checked) {
$("input.groupestimate").removeAttr("disabled");
} else {
$("input.groupestimate").attr("checked", false);
$("input.groupestimate").attr("disabled", true);
}
});
$("input.groupgatepass").attr("disabled", true);
$('input[name=gatepass]').click(function(){
if (this.checked) {
$("input.groupgatepass").removeAttr("disabled");
} else {
$("input.groupgatepass").attr("checked", false);
$("input.groupgatepass").attr("disabled", true);
}
});
/*
$('input.groupestimate').click(function() {
if(this.checked) {
$form = $('#globalSearch form');
if($('#globalSearch form[ACTION*="'+this.value+'"]'))
var data = new Object();
data.field = this.value;
var dataString = $.toJSON(data);
$.post('json.php',
{data: dataString},
function(res){
var obj = $.evalJSON(res);
$form.attr('ACTION',$form.attr('action')+''+obj.query);
}
);
}
});*/
$('#globalSearch form').submit(function() {
if($('input.groupheader[type=checkbox]:checked').length > 1) {
alert('Please check only Estimate or Gatepass');
return false;
}
var data = new Object();
$('input.groupheader[type=checkbox]:checked').each(function(){
data.header = this.value;
});
data.fields = new Array();
$header = 'input.group'+data.header;
$($header+'[type=checkbox]:checked').each(function(){
data.fields.push(this.value);
});
var dataString = $.toJSON(data);
$.post('json.php',
{data: dataString},
function(res){
var obj = $.evalJSON(res);
$('input[name=query]').val(obj.query);
}
);
alert($('input[name=query]').val()); //alerts nothing or the old value :(
return false;
});
});
</script>
-------------HTML PART-------------------
<form action="?<?php echo http_build_query(cloneGet(array("server-page"=>$GLOBALS["setting"]["current_folder"], "currpage"=>"0","OrderBy"=>"","ByDirect"=>"","search_flg"=>"-1")));?>" method="post" id="" name="">
<div id="extraSearch">
<table class="stripe" width="100%" id="extraTableList">
<tbody>
<tr class="striped">
<th style="cursor:pointer;text-align:left;"><input type="checkbox" name="estimate" value="estimate" checked="checked" class="groupheader">Estimates</th>
<th style="cursor:pointer;text-align:left;"><input type="checkbox" name="gatepass" value="gatepass" class="groupheader">Gatepass</th>
</tr>
<tr>
<td class="int"><input type="checkbox" name="estimate1" value="customer" class="groupestimate">Customer</td>
<td class="int"><input type="checkbox" name="gatepass1" value="old_serial" class="groupgatepass">Old Serial</td>
</tr>
<tr>
<td class="int"><input type="checkbox" name="estimate2" value="serial_no" class="groupestimate">Serial No</td>
<td class="int"><input type="checkbox" name="gatepass2" value="type" class="groupgatepass">Type</td>
</tr>
<tr>
<td class="int"><input type="checkbox" name="estimate3" value="invoice_no" class="groupestimate">Invoice No</td>
<td class="int"><input type="checkbox" name="gatepass3" value="type_id" class="groupgatepass">Type ID</td>
</tr>
<tr>
<td class="int"><input type="checkbox" name="estimate4" value="salesman" class="groupestimate">Salesman</td>
<td class="int"><input type="checkbox" name="gatepass4" value="loader" class="groupgatepass">Loader</td>
</tr>
<tr>
<td class="int"><input type="checkbox" name="estimate5" value="estimate_no" class="groupestimate">Estimate No</td>
<td class="int"><input type="checkbox" name="gatepass5" value="total" class="groupgatepass">Total</td>
</tr>
<tr>
<td class="int"><input type="checkbox" name="estimate6" value="status" class="groupestimate">Status</td>
<td class="int"> </td>
</tr>
</tbody>
</table>
</div>
<img id="searchicon" src="___images/search-arrow.png" class="toappear" alt="Extra search" title="Extra search"/>
<img id="searchicon2" src="___images/search-arrow.png" class="appear" alt="Extra search" title="Extra search"/>
<input type="text" value="<?php echo $_REQUEST['quicksearch'];?>" id="s" name="quicksearch">
<input type="hidden" value="" id="query" name="query" temp="">
<input type="submit" value="Search" id="b">
<?php if( $_REQUEST['quicksearch'] ) { ?>
<a id="c" href="?<?php echo http_build_query(cloneGet(array("quicksearch"=>"","search_flg"=>"-1")));?>">Cancel</a>
<?php } ?>
</form>
As you can see, before it submits the values I want to insert a string into the 'query' input element value attribute. It works perfectly when doing it inside the callback of $.post but after checking it using alert() outside the $.post its empty.
Is $.post always like that?or am I missing something?
when you are using $.post it is making an async request. The reason alert will contain nothing or the old value is because it is triggered before the $.post can complete its request. When the alert is placed inside of the $.post callback it will have the data you want because it is called after the $.post has completed

Contact form - success message

I am using a contact form and at the moment when you submit your details you are brought to a new page with a "thank you" message. I don't want users to be re-directed to a new page and instead I would like the "thank you" message to be displayed on the same page as the form. The code I am using is below.
Contact form code:
<form name="htmlform" method="post" action="html_form_send.php">
<table width="450px">
</tr>
<tr>
<td valign="top">
<label for="first_name">First Name *</label>
</td>
<td valign="top">
<input type="text" name="first_name" maxlength="50" size="30">
</td>
</tr>
<tr>
<td valign="top"">
<label for="last_name">Last Name *</label>
</td>
<td valign="top">
<input type="text" name="last_name" maxlength="50" size="30">
</td>
</tr>
<tr>
<td valign="top">
<label for="email">Email Address *</label>
</td>
<td valign="top">
<input type="text" name="email" maxlength="80" size="30">
</td>
</tr>
<tr>
<td valign="top">
<label for="telephone">Telephone Number</label>
</td>
<td valign="top">
<input type="text" name="telephone" maxlength="30" size="30">
</td>
</tr>
<tr>
<td valign="top">
<label for="comments">Comments *</label>
</td>
<td valign="top">
<textarea name="comments" maxlength="1000" cols="25" rows="6"></textarea>
</td>
</tr>
<tr>
<td colspan="2" style="text-align:center">
<input type="submit" value="Submit">
</td>
</tr>
</table>
</form>
PHP code to send form:
<?php
if(isset($_POST['email'])) {
// CHANGE THE TWO LINES BELOW
$email_to = "you#yourdomain.com";
$email_subject = "website html form submissions";
function died($error) {
// your error code can go here
echo "We are very sorry, but there were error(s) found with the form you submitted. ";
echo "These errors appear below.<br /><br />";
echo $error."<br /><br />";
echo "Please go back and fix these errors.<br /><br />";
die();
}
// validation expected data exists
if(!isset($_POST['first_name']) ||
!isset($_POST['last_name']) ||
!isset($_POST['email']) ||
!isset($_POST['telephone']) ||
!isset($_POST['comments'])) {
died('We are sorry, but there appears to be a problem with the form you submitted.');
}
$first_name = $_POST['first_name']; // required
$last_name = $_POST['last_name']; // required
$email_from = $_POST['email']; // required
$telephone = $_POST['telephone']; // not required
$comments = $_POST['comments']; // required
$error_message = "";
$email_exp = '/^[A-Za-z0-9._%-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if(!preg_match($email_exp,$email_from)) {
$error_message .= 'The Email Address you entered does not appear to be valid.<br />';
}
$string_exp = "/^[A-Za-z .'-]+$/";
if(!preg_match($string_exp,$first_name)) {
$error_message .= 'The First Name you entered does not appear to be valid.<br />';
}
if(!preg_match($string_exp,$last_name)) {
$error_message .= 'The Last Name you entered does not appear to be valid.<br />';
}
if(strlen($comments) < 2) {
$error_message .= 'The Comments you entered do not appear to be valid.<br />';
}
if(strlen($error_message) > 0) {
died($error_message);
}
$email_message = "Form details below.\n\n";
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
$email_message .= "First Name: ".clean_string($first_name)."\n";
$email_message .= "Last Name: ".clean_string($last_name)."\n";
$email_message .= "Email: ".clean_string($email_from)."\n";
$email_message .= "Telephone: ".clean_string($telephone)."\n";
$email_message .= "Comments: ".clean_string($comments)."\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);
?>
<!-- place your own success html below -->
Thank you for contacting us. We will be in touch with you very soon.
<?php
}
die();
?>
If you're wanting to refresh the page to the same location on which the form is located and display the results on the same page, then you could try this:
replace
<form name="htmlform" method="post" action="html_form_send.php">
with the following (so that you refresh the same page as the form).
<form name="htmlform" action="" method="post">
Adjust your submit button by giving it a name:
<input type="submit" name="submit" value="Submit">
and then validate whether the post has been submitted by checking if 'submit is set, rather than email...
if(isset($_POST['submit'])) { rather than if(isset($_POST['email'])) {
Then move the thankyou message code from the file 'html_form_send.php' to above your form code in the original file.
This should POST the data from the form to the same page on which the form is located, and only display the thank you message if the page detects that the form has been submitted... So long as you enclose any printed/echo'd thank you message inside the if(isset($_POST['submit'])) { brackets - i.e. in here } then it should work.
If you want to check if the form has been submitted without refreshing the page you'll need to look in to AJAX, but that is a bit more complicated.