I want to make a contact form and my problem is :
by the option select the contact type (peter or Michael) , if i want to contact for example peter and press the submit button it the form goes to his email example peter#gmail.com and so on.... how to solve the problem inside (select option && contact_procees code) please advise me
//// contact.php /////
<form class="contact-form" method="post" name="contact" id="f">
<table width="85%" border="0" cellspacing="0" cellpadding="0">
<td>Contact Person :</td>
**strong text** <td><select id="agents">
<option value="1">Peter</option>
<option value="2">Michael</option>
</select>
</td>
</tr>
<tr>
<td valign="top">Text :</td>
<td><textarea style="background-color:#f5f5f5; color:#000" name="msg" type="text" class="contact-textarea"></textarea></td>
</tr>
</table>
<br />
<br />
<table width="60%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="150px"></td>
<td align="left">
<input type="reset" class="submit" value="Reset" />
<input type="submit" class="submit" value="Send" onclick="sendForm(); return false;" id="btn" />
</td>
</tr>
</table>
</form>
/// JAVA SCRIPT CODE SEND FOR
<script type="text/javascript">
function sendForm() {
document.getElementById('btn').value=".....";
var oData = new FormData(document.forms.namedItem("contact"));
var oReq = new XMLHttpRequest();
oReq.open("POST", "contact_proccess.php", true);
oReq.onload = function(oEvent) {
if (oReq.status == 200) {
if(oReq.responseText=="1")
alert("Thankyou, the message is sent .");
else
alert("There was error in proccessing your request.Please try again later");
} else {
alert("There was error in proccessing your request.Please try again later");
}
document.getElementById("f").reset();
document.getElementById('btn').value="Send";
};
oReq.send(oData);
}
</script>
//// contact_process.php
<?php
error_reporting(0);
echo "1";
function error(){
exit("0");
}
if(!isset($_POST['name']) or !isset($_POST['work']) or !isset($_POST['subject']) or !isset($_POST['msg'])){
error();
}
$name=$_POST['name'];
$work=$_POST['work'];
$subject=$_POST['subject'];
$msg=$_POST['msg'];
if($name=="" or $work=="" or $subject=="" or $msg==""){
error();
}
$message=
<strong>Name</strong> : '.$_POST['name'].'<br>
<strong>Work</strong> : '.$_POST['work'].'<br>
<strong>contact</strong> : '.$_POST['subject'].'<br>
<strong>Text</strong> : '.$_POST['msg'].'<br>
</div>';
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
// More headers
$headers .= 'From:Mypage Website <webmaster#mypage.com>' . "\r\n";
$subject="Contact";
$to="peter#gamail.com"; /// what should i do for others
mail($to,$subject,$message,$headers);
?>
You can put your email id in select value like
<select id="agents" name="agents">
<option value="peter#gmail.com">Peter</option>
<option value="michael#gmail.com">Michael</option>
</select>
Get it in php like
$to = $$_POST['agents'];
and then send the email like you are sending
mail($to,$subject,$message,$headers);
I hope answred the question.
I would POST the form to a page called "sendmail.php" and there pick up the selected value (peter/micheal).
You can name them 1 and 2 if you like.
The thing about having it javascript or in the html code is that the mail is in plain sight.
There are robots crawling for mails and the mails printed in html are a likely victim.
Once the send has been done you could echo out thank you and it worked, or did not work.
But my advice is POST the values and send them in php, that way it's secure from crawlers
Related
EDIT
I have implemented the changes suggested and I still cant get this to work:
Form Page Follows (login.php)
<?php
$mac=$_POST['mac'];
$ip=$_POST['ip'];
$username=$_POST['username'];
$linklogin=$_POST['link-login'];
$linkorig=$_POST['link-orig'];
$error=$_POST['error'];
$chapid=$_POST['chap-id'];
$chapchallenge=$_POST['chap-challenge'];
$linkloginonly=$_POST['link-login-only'];
$linkorigesc=$_POST['link-orig-esc'];
$macesc=$_POST['mac-esc'];
if (isset($_POST['postcode'])) {
$postcode = $_POST['postcode'];
}
if (isset($_POST['email'])) {
$email = $_POST['email'];
}
?>
**SOME HTML HERE**
<script src="jquery-3.2.1.min.js"></script>
<script>
var js-postcode = document.login.getElementsByName("postcode").value;
var js-email = document.login.getElementsByName("email").value;
var formdata = {postcode:js-postcode,email:js-email};
$("button").click(function(){
$.ajax(
{
type: "POST",
url: "database.php", //Should probably echo true or false depending if it could do it
data : formdata,
success: function(feed) {
if (feed!="true") {
// DO STUFF
} else {
console.log(feed);
// WARNING THAT IT WASN'T DONE
}
}}}
</script>
</head>
<body>
<table width="100%" style="margin-top: 10%;">
<tr>
<td align="center" valign="middle">
<table width="240" height="240" style="border: 1px solid #cccccc; padding: 0px;" cellpadding="0" cellspacing="0">
<tr>
<td align="center" valign="bottom" height="175" colspan="2">
<!-- removed $(if chap-id) $(endif) around OnSubmit -->
<form name="login" action="<?php echo $linkloginonly; ?>" method="post" onSubmit="return doLogin()" >
<input type="hidden" name="dst" value="<?php echo $linkorig; ?>" />
<input type="hidden" name="popup" value="true" />
<table width="100" style="background-color: #ffffff">
<tr><td align="right">login</td>
<td><input style="width: 80px" name="username" type="text" value="<?php echo $username; ?>"/></td>
</tr>
<tr><td align="right">password</td>
<td><input style="width: 80px" name="password" type="password"/></td>
</tr>
<tr><td align="right">Postcode</td>
<td><input style="width: 80px" name="postcode" type="text" /></td>
</tr>
<tr><td align="right">Email</td>
<td><input style="width: 80px" name="email" type="text" /></td>
</tr>
<td><button><input type="submit" value="OK" /></button></td>
</tr>
</table>
</form>
</td>
</tr>
</table>
</td>
</tr>
</table>
<script type="text/javascript">
<!--
document.login.username.focus();
//-->
</script>
</body>
</html>
and called file database.php is as follows:
<?php
if ((isset($_POST['postcode'])) && (isset($_POST['email']))) {
$postcode = $_POST['postcode'];
$email = $_POST['email'];
$connect= new mysqli_connect('xx','xx','xx','xx');
if ($conn->connect_errno) {
echo "There was a problem connecting to MySQL: (" . $conn->connect_errno . ") " . $conn->connect_error;
}
if (!($sql = $conn->prepare("INSERT INTO visitors(postcode,email) VALUES(postcode,email)"))) {
echo "Prepare failed: (" . $conn->errno . ") " . $conn->error;
}
//NOTE: the "ss" part means that $postcode and $email are strings (mysql is expecting datatypes of strings). For example, if $postcode is an integer, you would do "is" instead.
if (!$sql->bind_param("ss", $postcode, $email)) {
echo "Binding parameters failed: (" . $sql->errno . ") " . $sql->error;
}
if (!$sql->execute()) {
echo "Execute failed: (" . $sql->errno . ") " . $sql->error;
}
} else {
echo 'Variables did not send through ajax.'; // any echoed values would be sent back to javascript and stored in the 'response' variable of your success or fail functions for testing.
}
?>
Still I get nothing fed through from the form to the database. Even if I swap the variables for strings I get nothing through to the database however if I run database.php separately it works. Surely Im close to getting this working now .. any help appreciated and thanks so much for the assistance provided so far.
*************************** ORIGINAL QUESTION FOLLOWS *******************
I have a simple form as follows:
<form name="login" action="somethingelse.php" method="post" onSubmit="return doLogin()" >
<input type="hidden" name="dst" value="<?php echo $linkorig; ?>" />
<input type="hidden" name="popup" value="true" />
<table width="100" style="background-color: #ffffff">
<tr><td align="right">login</td>
<td><input style="width: 80px" name="username" type="text" value="<?php e$
</tr>
<tr><td align="right">password</td>
<td><input style="width: 80px" name="password" type="password"/></td>
</tr>
<tr><td align="right">Postcode</td>
<td><input style="width: 80px" name="postcode" type="text" /></td>
</tr>
<tr><td align="right">Email</td>
<td><input style="width: 80px" name="email" type="text" /></td>
</tr>
<td><button><input type="submit" value="OK" /></button></td>
</tr>
</table>
</form>
Because I need to use the form action to do something else, I need to use jQuery on the click of the button to send data to a database. Specifically the postcode and email address taken from the form. The part of the code relating to the jQuery is shown below:
<script language="JavaScript" >
$(document).ready(function(){
$("button").click(function(){
mysqli_query();
});
});
</script>
The called function mysqli_query is declared via an include statement and therefore lives in a different file. The function called is shown below:
mysqli_query( $connect, "INSERT INTO visitors(postcode,email) VALUES(postcode,email)");
I have been going round in circles for days with this. I know Im close to making it work but cant quite cross the finish line. Could somebody please point out what I'm doing wrong here?
WARNING: Never ever trust user input, always sanitize the input first AND use prepared statements otherwise, you're leaving youself vulnerable to SQL INJECTION ATTACKS
You're mixing up, Javascript is a clientside language, and mysqli is a PHP based function on the serverside of things.
What you should be doing is an ajax call with the values to a different PHP file that will make the database connection and insert the data.
var dataString = "postcode="+ postcode+"&email="+email;
$.ajax({
type: "POST",
url: "file_that_does_the_work.php", //Should probably echo true or false depending if it could do it
data: dataString,
success: function(feed) {
if (feed=="true") {
// DO STUFF
} else {
console.log(feed);
// WARNING THAT IT WASN'T DONE
}
}
file_that_does_the_work.php
<?
include("config.php"); // your thing that configures the connection
$postcode = sanitizationfunction($_POST["postcode"]);
$email = sanitizationfunction($_POST["email"]);
$query = $connection->prepare('INSERT INTO visitors(postcode,email) VALUES(?,?)');
$query->bindParam(1, $postcode);
$query->bindParam(2, $email);
if ($query->execute()) {
echo "true";
} else {
echo "false";
}
?>
form.php
<table width="100" style="background-color: #ffffff">
<tr><td align="right">login</td>
<td><input style="width: 80px" name="username" type="text" value="<?php echo $username?>"/>
</tr>
<tr><td align="right">password</td>
<td><input style="width: 80px" name="password" type="password"/></td>
</tr>
<tr><td align="right">Postcode</td>
<td><input style="width: 80px" name="postcode" type="text" /></td>
</tr>
<tr><td align="right">Email</td>
<td><input style="width: 80px" name="email" type="text" /></td>
</tr>
<td><input type="submit" value="OK" /></td>
</tr>
</table>
</form>
`
somethingelse.php
<?php
foreach ($_POST as $key => $value) {
echo $key."=".$value."<br/>";
}
?>
I leave connectivity part to you :D
So, as others have pointed out, you are mixing up your client-side code and your server-side code. You need to send all the form data to a php file. The jquery ajax will send the data over to the script, and determine if this call was successful or not. If the call is not successful, you can run test logic. If it is, than you can do other logic, such as alert the user of a successful form submit.
Below is an example of the process:
ajax:
<script>
var formData = 'some data' // Get your form values and save here - postcode and email
$("button").click(function(){
$.ajax ({
method: 'POST',// you can do either post or get...
url: "page_to_handle_mysql_code.php",
data: formData
success: function( response ) {
//do something like alert("Submitted Successfully!");
}
fail: function( response) {
//Do testing such as console.log(response); NOTE: Response will be what ever your php page sends back.
}
});
)};
</script>
On your php page: page_to_handle_mysql_code.php
<?php
if ((isset($_POST['postcode'])) && (isset($_POST['email']))) {
$postcode = $_POST['postcode'];
$email = $_POST['email'];
//connect to mysql - I prefer prepared statements as the variables are prepared for safety when sent to MySQL
$conn = new mysqli($servername, $username, $password, $dbname);//you can either put the actually values in, or I include another php page in this one that sets my variables so I can resuse my code easily.
if ($conn->connect_errno) {
echo "There was a problem connecting to MySQL: (" . $conn->connect_errno . ") " . $conn->connect_error;
}
if (!($sql = $conn->prepare("INSERT INTO visitors(postcode,email) VALUES(?,?)"))) {
echo "Prepare failed: (" . $conn->errno . ") " . $conn->error;
}
//NOTE: the "ss" part means that $postcode and $email are strings (mysql is expecting datatypes of strings). For example, if $postcode is an integer, you would do "is" instead.
if (!$sql->bind_param("ss", $postcode, $email)) {
echo "Binding parameters failed: (" . $sql->errno . ") " . $sql->error;
}
if (!$sql->execute()) {
echo "Execute failed: (" . $sql->errno . ") " . $sql->error;
}
} else {
echo 'Variables did not send through ajax.'; // any echoed values would be sent back to javascript and stored in the 'response' variable of your success or fail functions for testing.
}
?>
This should help you get your values entered to MySQL. I hope it helps!
You can submit a form with jquery
mysqli_query is a function in your PHP, your javascript doesn't have access to the function. You have to make an http call from your javascript, which your PHP will receive and run mysqli_query on its end
I want to fill the form and able to return back to modify the records. But when I return back I want the form to have the previous values. when I put " />
I got error.
please help
Thank you!
My code
<?php
if (isset($_POST['submit'])) {
$from = 'hello#gmail.com';
$subject = $_POST['subject'];
$text = $_POST['elvismail'];
$output_form = false;
if(empty($subject) && empty($text)) {
echo 'You forgot the email subject and body text.<br />';
$output_form = true;
}
if (empty($subject) && (!empty($text))) {
echo 'You forgot the email subject.<br />';
$output_form = true;
}
if ((!empty($subject)) && empty($text)) {
echo 'You forgot the email body text.<br />';
$output_form = true;
}
if ((!empty($subject)) && (!empty($text))) {
if(isset($_POST['cancel'])) {
echo "cancel";
}
else if(isset($_POST['send'])) {
echo "submit";
}
?>
<form method="post" action="index.php">
<table>
<tr>
<td>Subject of email</td>
<td> <?php echo $subject; ?> </td>
</tr>
<tr>
<td>Body of email</td>
<td><?php echo $text ?> </td>
</tr>
</table>
<input type="submit" name="cancel" value="cancel" />
<input type="submit" name="send" value="Submit" />
</form>
<?php
}
}
else {
$output_form=true;
}
if ($output_form) {
?>
<form method="post" action="index.php">
<label for="subject">Subject of email:</label><br />
<input id="subject" name="subject" type="text" size="30" /><br />
<label for="elvismail">Body of email:</label><br />
<textarea id="elvismail" name="elvismail" rows="8" cols="40"></textarea><br />
<input type="submit" name="submit" value="Submit" />
</form>
<?php
}
?>
In this scenario its much better to use client side resources rather than storing it again on php. Because it is just a temporary value and using Local Storage would benefit you alot.
Javascript or JQuery would be the best approach to accomplish this.
Step 1 : Store the value on LocalStorage after on blur of every input on the form.
Step 2 : When user gets back to page. Simply assign the last data you saved on the localStorage
Because if you refresh the page you will lose the data variables in your php and will require to fetch it again on the database thus resulting on the same data values.
I suggest you read about the LocalStorage and read about controlling inputs with JQuery.
x = $("#form").serialize();
localStorage.setItem("temp_form_data" , x);
// To retrieve it simply convert it to JSON and assign it to each inputs.
var temp = JSON.parse(localStorage.getItem("temp_form_data"));
$("your-input-target").value(temp.id);
$("other-input-target").value(temp.description);
//and so on
This is just what would the implementation look like for setting and getting input data.
I am trying to display a table from my PHP file on a web page which is the index.html file using ajax. I am new to PHP and ajax so I currently do not know what is wrong with the codes. However what I do know is that there data is not getting through this line in the javascript file.
document.getElementById("divTable").innerHTML=xmlhttp.responseText;
It works without ajax but of course I do need to go to database.php to display the table. I want it to display on index.html. Also, will my delete button in my PHP file still work?
P.S. I'm using vi editor as I'm currently coding this on a server. However it's just to test out. I am new to server stuff, ajax and PHP so do pardon my mistakes if any. And ignore the table formatting in my HTML file.
P.P.S I do not know any form of jQuery and what I have written is my current knowledge of AJAX.
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css"/>
<script src="function.js" type="text/javascript"></script>
</head>
<body>
<form name="infoForm" method="post" onsubmit="return checkFields()" action="">
<table>
<tr>
<td>Name:</td>
<td><input type="text" name="name" id="name" maxlength="40"></td>
</tr>
<tr>
<td>Address:</td>
<td><textarea maxlength="45" name="address"id="address" ></textarea></td>
</tr>
<tr>
<td>Phone:</td>
<td><input type="text" name="phone" id="phone" maxlength="20"><br></td>
</tr>
<tr>
<td>Gender:</td>
<td><input checked type="radio" name="gender" id="male" value="Male">Male
<input type="radio" name="gender" id="female" value="Female">Female</td>
</tr>
<tr>
<td>
Nationality:
</td>
<td>
<select name="nation">
<option value="Singapore">Singapore</option>
<option value="Malaysia">Malaysia</option>
<option value="Thailand">Thailand</option>
<option value="Indoensia">Indonesia</option>
<option value="Philippines">Philippines</option>
</select>
</td>
</tr>
<tr>
<td></td>
<td>
<br><input type="reset" value="Cancel">
<input type="submit" name="result" value="Submit" onclick="checkFields()"/>
</td>
</tr>
</table>
</form>
<div id="divTable"></div>
</body>
</html>
This is my javascript file, function.js:
function checkFields(){
var name = document.getElementById("name");
var address = document.getElementById("address");
var phone = document.getElementById("Phone");
if(confirm('Do you want to submit')){
if(name == null, name == ""||address == null, address == ""||phone == null, phone == ""){
alert("Please fill in all your details.");
return false;
}
else{
var page = "database.php";
var xmlhttp = new XMLHttpRequest();
if(xmlhttp==null){
alert("Your browser does not support AJAX!");
return false;
}
xmlhttp.onreadystatechange=function(){
document.getElementById("divTable").innerHTML=xmlhttp.responseText;
}
xmlhttp.open("GET", page, true);
xmlhttp.send(null);
}
}
else{
return false;
}
}
This is my PHP file, database.php:
<?php
// Define database parameters //
DEFINE ('DB_USER' ,'iqwer222');
DEFINE ('DB_PASSWORD', 'wfwqr');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'aqwfvaqf');
$table_info = "info";
// Connect to database
$conn = #mysql_connect (DB_HOST, DB_USER, DB_PASSWORD) OR die ('Could not connect to Database:'. mysql_error());
#mysql_select_db (DB_NAME) OR die ('Could not select the Database: '.mysql_error());
// Delete Row
if(isset($_POST['delete'])){
$id = $_POST['deleteRow'];
$query_string = "delete from $table_info where user_id='$id'";
$result = #mysql_query($query_string);
}
//Check if phone no. is duplicate and if not, insert data
if(isset($_POST['result'])){
$phone = $_POST['phone'];
$query_string = "select phone from $table_info where phone='$phone'";
$result = #mysql_query($query_string);
$num_row = mysql_num_rows($result);
if($num_row){
echo "A same phone number has been found. Please enter a different phone number.";
}else{
$query_string = "insert into $table_info(name, address, phone, gender, nation) values('".$_POST['name']."','".$_POST['address']."','".$_POST['phone']."','".$_POST['gender']."','".$_POST['nation']."')";
$result = #mysql_query($query_string);
}
}
// Display table
$query_string = "select * from $table_info";
$result = #mysql_query($query_string);
$num_row = mysql_num_rows($result);
if($num_row){
echo "<table border=1>";
echo "<tr><th>Name</th><th>Address</th><th>Phone no.</th><th>Gender</th><th>Nationality</th><th>Created</th><th>Modified</th><th>Action</th></tr>";
while($row = mysql_fetch_array($result)){
echo "<tr><td>", $row['name'], "</td>";
echo "<td>", $row['address'], "</td>";
echo "<td>", $row['phone'], "</td>";
echo "<td>", $row['gender'], "</td>";
echo "<td>", $row['nation'], "</td>";
echo "<td>", $row['createdTime'], "</td>";
echo "<td>", $row['modifiedTime'], "</td>";
?>
<!--Delete button-->
<td><form id="delete" method="post" action="">
<input type="hidden" name="deleteRow" value="<?php echo $row['user_id'] ?>"/>
<input type="submit" name="delete" value="Delete" onclick="return confirm('Are you sure you want to delete this contact?')"/></td></form></tr>
<?php
}
echo "</table>";
}
else{
echo "0 results";
}
?>
<form method="post" action="index.html">
<input type="submit" name="goBack" value="Back"/>
</form>
Considering that you database.php file is giving out correct data back.
a) Error :-
You are not using return false on form submit handler , just add return false and things will work for you
b) Suggestion
1) You are attaching the checkFields() function 2 times, once on submit button click and other on form submit, remove one of them(use sumbit)
2) User below callback in onreadystatechange , the one you have done will work but it is not correct as this callback get called mulitple times
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("divTable").innerHTML=xmlhttp.responseText;
}
}
Example Code below :
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css"/>
<script >
function checkFields(){
var name = document.getElementById("name");
var address = document.getElementById("address");
var phone = document.getElementById("Phone");
if(confirm('Do you want to submit')){
if(name == null, name == ""||address == null, address == ""||phone == null, phone == ""){
alert("Please fill in all your details.");
return false;
}
else{
var page = "database.php";
var xmlhttp = new XMLHttpRequest();
if(xmlhttp==null){
alert("Your browser does not support AJAX!");
return false;
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("divTable").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET", page, true);
xmlhttp.send(null);
}
}
return false;
}
</script>
</head>
<body>
<form name="infoForm" method="post" onsubmit="return checkFields()" action="">
<table>
<tr>
<td>Name:</td>
<td><input type="text" name="name" id="name" maxlength="40"></td>
</tr>
<tr>
<td>Address:</td>
<td><textarea maxlength="45" name="address"id="address" ></textarea></td>
</tr>
<tr>
<td>Phone:</td>
<td><input type="text" name="phone" id="phone" maxlength="20"><br></td>
</tr>
<tr>
<td>Gender:</td>
<td><input checked type="radio" name="gender" id="male" value="Male">Male
<input type="radio" name="gender" id="female" value="Female">Female</td>
</tr>
<tr>
<td>
Nationality:
</td>
<td>
<select name="nation">
<option value="Singapore">Singapore</option>
<option value="Malaysia">Malaysia</option>
<option value="Thailand">Thailand</option>
<option value="Indoensia">Indonesia</option>
<option value="Philippines">Philippines</option>
</select>
</td>
</tr>
<tr>
<td></td>
<td>
<br><input type="reset" value="Cancel">
<input type="submit" name="result" value="Submit" />
</td>
</tr>
</table>
</form>
<div id="divTable"></div>
</body>
</html>
This question already has answers here:
Prevent Form resubmission upon hitting back button
(10 answers)
Closed 8 years ago.
I'm developing a php emailer that uses a form which needs to redirect to a "thank you" page that I don't have access to for the purpose of adding code. User input is sent through some simple preg_match functions to make sure it matches the necessary format. If it fails one of these functions, a javascript popup is echoed letting the user know what they need to change. If it makes it through, the data is stored in SESSION variables, and passed to a page where the data is added to the necessary html, and sent as a simple html email. The process.php page then redirects to results.php which clears out the session, and takes the user to the "thank you" page.
My problem is that when the user enters bad data then corrects it and submits, pressing the 'back' button after arriving at the "thank you" page gets me one of these "confirm form resubmit" pages before it goes back to the form. Once it actually gets back to the form after hitting 'back' a second time, the old, bad data is in the form in place of the good stuff. I would like to fix it so the "confirm form resubmit" page never appears, and the user is returned to a blank form if they hit the back button only once. My html:
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<table id="form_table" style="280px; border:0px; padding: 0 0 5px 0; border-spacing: 0px;">
<tr>
<td>
<span style="font-size: 12px;">*First name</span>
</td>
</tr>
<tr>
<td>
<input style="padding: 5px; font-size: 12px;" name="firstName" type="text" size="50" value="<?php if(isset($_POST['firstName'])) { echo htmlentities($_POST['firstName']); }?>" />
</td>
</tr>
<tr>
<td style="padding-top: 7px;">
<span style="font-size: 12px;">*Last name</span>
</td>
</tr>
<tr>
<td>
<input style="padding: 5px; font-size: 12px;" name="lastName" type="text" size="50" value="<?php if(isset($_POST['lastName'])) { echo htmlentities($_POST['lastName']); }?>" />
</td>
</tr>
<tr>
<td style="padding-top: 7px;">
<span style="font-size: 12px;">*Email</span>
</td>
</tr>
<tr>
<td>
<input style="padding: 5px; font-size: 12px;" name="emailAddy" type="text" size="50" value="<?php if(isset($_POST['emailAddy'])) { echo htmlentities($_POST['emailAddy']); }?>" />
</td>
</tr>
<tr>
<td style="padding-top: 7px;">
<span style="font-size: 12px;">Phone number</span>
</td>
</tr>
<tr>
<td>
<input style="padding: 5px; font-size: 12px;" name="phoneNumber" type="text" size="50" value="<?php if(isset($_POST['phoneNumber'])) { echo htmlentities($_POST['phoneNumber']); }?>" />
</td>
</tr>
<tr>
<td style="padding-top: 15px;">
<span style="font-size: 12px;">Tell us how we can help</span>
</td>
</tr>
<tr>
<td>
<input style="padding: 5px 5px 15px 5px; font-size: 12px;" name="howHelp" type="text" size="50" value="<?php if(isset($_POST['howHelp'])) { echo htmlentities($_POST['howHelp']); } ?>" />
</td>
</tr>
</table>
<div style="width: inherit;">
<input type="image" id="saveform" src="http://www.fivemm.com/client/tristar/images/consult-btn.jpg" alt="Submit Question!" style="width: 100%; height: 96px; border: none;" />
</div>
<?php echo $msg_to_user ?>
</form>
The processing code, located on the bottom of the same page:
<?php
if(isset($_POST['firstName'])) {
function died($error) {
$error = 'So sorry, but it looks like there are some issues with your form.\\n\\n'.$error;
echo '<script type="text/javascript"> alert("'.$error.'")</script>';
die();
}
$error_message = "";
$email_exp = '/^[A-Za-z0-9._%-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
$string_exp = "/^[A-Za-z .'-]+$/";
$msg_exp = "/^$|^[A-Za-z ?!.'-:]+$/";
if(!preg_match($string_exp,$_POST['firstName'])) {
$error_message .= 'The first name you entered contains invalid characters or is blank.\\n\\n';
}
if(!preg_match($string_exp,$_POST['lastName']) && strlen($_POST['lastName']) > 0) {
$error_message .= 'The last name you entered contains invalid characters.\\n\\n';
}
if(!preg_match($email_exp,$_POST['emailAddy'])) {
$error_message .= 'The email address you entered does not appear to be valid or is blank.\\n\\n';
}
if(strlen($error_message) > 0) {
died($error_message);
}
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
$_SESSION['firstName'] = $_POST['firstName']; // required
$_SESSION['lastName'] = $_POST['lastName']; // required
$_SESSION['emailAddy'] = $_POST['emailAddy']; // required
$_SESSION['phoneNumber'] = htmlspecialchars(clean_string($_POST['phoneNumber'])); // required
$_SESSION['howHelp'] = clean_string($_POST['howHelp']);
echo ("<SCRIPT LANGUAGE='JavaScript'>window.location.href='process.php';</SCRIPT>");
}
?>
The process.php page:
<?php
session_start();
if(isset($_SESSION['firstName']) && isset($_SESSION['page1'])) {
$_SESSION['page2']="2";
$first_name = $_SESSION['firstName'];
$last_name = $_SESSION['lastName'];
$email_addy = $_SESSION['emailAddy'];
$phone_number = $_SESSION['phoneNumber'];
$how_help = $_SESSION['howHelp'];
// EDIT THESE 2 LINES BELOW AS REQUIRED
$email_to = 'someguy#domainname.com'; // use for testing
$email_subject = "This Guy Wants To Contact You!"; // Enter intended message here
$email_message = '<html>';
$email_message .= '<head>';
$email_message .= '</head>';
$email_message .= '<body>';
$email_message .= '<h3>You have a new email message!</h3>';
$email_message .= '<table>';
$email_message .= '<tr><td>Name</td><td>'.$first_name.' '.$last_name.'</td></tr>';
$email_message .= '<tr><td>Email Address</td><td>'.$email_addy.'</td></tr>';
$email_message .= '<tr><td>Phone Number</td><td>'.$phone_number.'</td></tr>';
$email_message .= '<tr><td>How can we help?</td><td>'.$how_help.'</td></tr>';
$email_message .= '</table>';
$email_message .= '</body>';
$email_message .= '</html>';
// create email headers
$headers = "From: ".$first_name." \r\n";
$headers .= "Bcc: otherguy#otherdomain.com, otherdude#yetanotherdomain.com\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$headers .= "\r\n";
// $headers .= 'X-Mailer: PHP/' . phpversion();
#mail($email_to, $email_subject, $email_message, $headers);
header('Location: results.php');
}
?>
And finally, the results.php page:
<?php
session_start();
if (isset($_SESSION['page2']))
{
session_destroy();
header('Location: http://www.domainname.com/thank-you/');
}
else
{
header('Location: index.php');
}
?>
Short: you can't turn it off.
Long: You should move the processing of form to the beginning.
At first you check if form was submitted and if so you process the data.
On the other hand, when form was not submitted, you just show the form.
The idea here is that when you find errors on processing the data,
you can display the error message and also show the form again.
The good part here is that now you can fill the parts of form that are correct
with the $_POST values you got.
Something like this:
...
<input type="text" name="username" value="<?php echo $_POST["username"]?>" />
...
Now the user just fills the ones that had errors and resubmits.
If it passes you proceed with your email part.
Note that you should sanitize the $_POST array before you use it. ( look: stripslashes, trim, htmlspecialchars )
Hope I made myself clear :)
Sorry, it's late, so I made an example of what i meant:
sample php code
Well, I must admit, the code is a bit strange. As I can see, you have a PHP part in the form page, which test the value from the form. That's it?
I suggest to perform the Rexp in Javascript. Using this you will have a cleaner code: one form with JS for test, submit to process page.
In process page, if you want, you can perform another test, and in case of faillure, fill the session and go back to the form (in that case you will have to read the session).
Maybe the confirm before resubmit came from the fact the page is self-called.
Regards
Peter
I have the code
<form name="input" action="messagesave.php" method="POST">
<table style="margin-left: auto; margin-right: auto;">
<tr>
<td style="font-family:'Comic Sans MS', cursive; font-size:20px; text-shadow: 0 0 10px #FFFFFF;">Subject:</td>
</tr>
<tr>
<td><input type="text" value="(Optional)" name="sub" onblur="this.value=!this.value?'(Optional)':this.value;" onfocus="this.select()" onclick="this.value='';"></td>
</tr>
<tr>
<td style="font-family:'Comic Sans MS', cursive; font-size:20px; text-shadow: 0 0 10px #FFFFFF;">Message (Required):</td>
</tr>
<tr>
<td><textarea name="comment" id="comment" cols="60" rows="6"></textarea></td>
</tr>
<tr>
<td>
<?php
require_once('recaptchalib.php');
$publickey = "6LeSzekSAAAAAL32gFlK_vGcqI3-kuoz990KSJHU"; // you got this from the signup page
echo recaptcha_get_html($publickey);
?>
</td>
</tr>
<tr>
<td><input type="submit" class="submit" value="Submit Message"></td>
</tr>
</table>
</form>
on the main page with the action being
require_once('recaptchalib.php');
$privatekey = "6LeSzekSAAAAAAdAxcsVugyScb8B1D6UoKpjrX2W";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." . "(reCAPTCHA said: " . $resp->error . ")");
}
else {
$comment = $_POST['comment'];
$to = "jsmith#example.com";
$subject = $_POST['sub'];
$message = $comment;
$from = "jsmith#example.net";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
echo "Mail Sent.";
header( 'Location: success.html' ) ;
}
When a user INCORRECTLY enters reCAPTCHA code the page is moved onto a blank page saying recaptcha was not entered correctly.
I want to ask, how can I implement either an javascript alert or red text that appears on the main page so users will not have to press the back button all the time.
Thanks
You have to send the form to the same PHP script itself with a parameter that indicates, that the form has been sent (send in this case):
<form name="input" action="?send" method="POST">
At the beginning of the same PHP script as the form is in check if the form is sent and the entered data is correct:
<?php
$errorArr = array();
if(isset($_GET['send'])) {
// form is sent, do your captcha and other checks here and save the errors in an array
if($captcha->wrong())
$errorArr[] = 'You entered the captcha wrong';
if(count($errorArr) <= 0) {
// No errors occured so do stuff with the correct input of the user
// save it to db for example
}
}
?>
Somewhere on your page you can then print out the error messages like
<?php echo (count($errorArr) > 0)?implode('<br>', $errorArr):null; ?>
Or you can do the whole thing with two different pages and session variables but this is imho to complicate and unnecessary.
If you use Ajax to check your captcha you still need to check it serverside again when the form is sent because someone can disable javascript (as most of the spambot can't interpret javascript) und your captcha veryfication fails.
In your case you end up with something like
<?php
require_once('recaptchalib.php');
$errorArr = array();
$privatekey = "6LeSzekSAAAAAAdAxcsVugyScb8B1D6UoKpjrX2W";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
$errorArr[] = 'The reCAPTCHA wasn\'t entered correctly. Go back and try it again. (reCAPTCHA said: ' . $resp->error . ')';
}
if(count($errorArr) <= 0) {
$comment = $_POST['comment'];
$to = "jsmith#example.com";
$subject = $_POST['sub'];
$message = $comment;
$from = "jsmith#example.net";
$headers = "From:" . $from;
if(mail($to,$subject,$message,$headers) === false)
$errorArr[] = 'Mail could not be sent to us due to a technical error';
// if headers are sent after output already sent you get an error
//echo "Mail Sent.";
header( 'Location: success.html' ) ;
}
?>
<form name="input" action="messagesave.php" method="POST">
<?php echo (count($errorArr) > 0)?implode('<br>', $errorArr):null; ?>
<table style="margin-left: auto; margin-right: auto;">
<tr>
<td style="font-family:'Comic Sans MS', cursive; font-size:20px; text-shadow: 0 0 10px #FFFFFF;">Subject:</td>
</tr>
<tr>
<td><input type="text" value="(Optional)" name="sub" onblur="this.value=!this.value?'(Optional)':this.value;" onfocus="this.select()" onclick="this.value='';"></td>
</tr>
<tr>
<td style="font-family:'Comic Sans MS', cursive; font-size:20px; text-shadow: 0 0 10px #FFFFFF;">Message (Required):</td>
</tr>
<tr>
<td><textarea name="comment" id="comment" cols="60" rows="6"></textarea></td>
</tr>
<tr>
<td>
<?php
require_once('recaptchalib.php');
$publickey = "6LeSzekSAAAAAL32gFlK_vGcqI3-kuoz990KSJHU"; // you got this from the signup page
echo recaptcha_get_html($publickey);
?>
</td>
</tr>
<tr>
<td><input type="submit" class="submit" value="Submit Message"></td>
</tr>
</table>
</form>
It is going to different page because i guess you are posting the form. What you can do is change your submit button to simple button. Then
$( "#button" ).click(function() {
//your ajax call to validating php
//on success $( "#formId" ).submit();
});
In case you don't want to use javascript just post the form and you can redirect it to the same page from your validation php with a variable set.
header("Location:http://localhost/login.php?x=1")
Check for
if(isset($_GET('x'))){
//your html for error message
}
Perhaps This POST can help
Combine your form and your action handling code into one script that posts to itself with the general form being:
if ($POST['submit'] && $resp->is_valid) {
// Form sent and captcha ok
} else {
// Check, was it submitted already?
if (isset($resp) && !$resp->is_valid) {
echo "<div><p>The reCAPTCHA wasn't entered correctly. Go back and try it again." . "(reCAPTCHA said: " . $resp->error . ")</p></div>";
}
// All the form code here.
}