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.
}
Related
This question already has answers here:
PHP Redirect with POST data
(13 answers)
Closed 5 years ago.
I'm fairly new to PHP. I have a form that a user is filling in with various details (start date, end date, etc), called purchaseLicence.php. When it is submitted, the form action reloads itself to use PHP to validate the data.
If validation is passed, I want it to navigate to purchaseLicence2.php using the post method, as though the form had originally posted directly to purchaseLicence2.php.
I don't mind involving Javascript to do this, and I'm guess that it would need to be involved as it will end up looking at a different form to the one it would otherwise expect to be on.
This is my current purchaseLicence.php, the problem I get is that both purchaseLicence2.php and purchaseLicence.php are rendered after the form has been posted, and the browser is still pointing to purchaseLicence.php, rather that purchaseLicence2.php.
<?php
include_once('php/strings.php');
include_once('php/sprocs.php');
include_once('php/dates.php');
$encounteredValidationError = false;
$navigateAway=false ;
if (isset($_POST['process']))
{
if ($_POST['process'] == 1)
{
// if here, form has been posted
$ProductCode = $_POST['ProductCode'];
$StartDate = $_POST['StartDate'];
$EndDate = $_POST['EndDateHidden'];
// standardise the date formats to ISO8601
$StartDate = date("Y-m-d", strtotime($StartDate));
$EndDate = date("Y-m-d", strtotime($EndDate));
echo "<descriptive>" . PHP_EOL;
echo "ProductCode:" . $ProductCode . "<br/>" . PHP_EOL;
echo "StartDate:" . $StartDate . "<br/>" . PHP_EOL;
echo "EndDate:" . $EndDate . "<br/>" . PHP_EOL;
echo "</descriptive>" . PHP_EOL;
// validation to happen here
if (!$encounteredValidationError)
{
// so we're happy with the values. The form has just reloaded, so we need to put these back from $_POST into the input fields, so
// that we can call NavigateToPurchaseLicence2(), which will get them out of the input fields and post them to purchaseLicence2.php
// What a faff!
$data = array('ProductCode'=>$ProductCode, 'StartDate'=>$StartDate, 'EndDate'=>$EndDate);
$options = array(
'http'=>array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents('purchaseLicence2.php', false, $context);
if ($result === FALSE) { /* Handle error */ }
var_dump($result);
}
else
{
// hilite errors in the form here, how? form is not yet loaded
}
}
}
?>
</head>
<body>
<form method="post" action="purchaseLicence.php" id="form1">
<input type="hidden" name="process" value="1">
<table border=0 width=800px align=left style="margin: 0px auto;">
<tr> <!-- Product > -->
<td style="vertical-align:top" width="500px" bgcolor="lightgray"><descriptive>Product</descriptive></td>
<td width="500px" bgcolor="lightgray">
<?php
// creates a dropdown of products
OutputSelectFromSQL("SELECT * FROM Product ORDER BY Description", "ProductCode", "ProductCode", "Description", "");
?>
</td>
</tr>
<tr> <!-- Licence Period -->
<td style="vertical-align:top" width="500px" bgcolor="lightgray"><descriptive>Licence Period</descriptive></td>
<td width="500px" bgcolor="lightgray"><descriptive>1 year</descriptive></td>
</tr>
<tr> <!-- Start Date -->
<td style="vertical-align:top" width="500px" bgcolor="lightgray"><descriptive>Start/End Dates</descriptive></td>
<td width="500px" bgcolor="lightgray">
<input type="date" style="font-family:verdana;font-size:12px;" name="StartDate" id="StartDate" onchange="updateEndDate(this.value);"></input>
<descriptive> to <a id="EndDate"></a></descriptive>
<input type="hidden" name="EndDateHidden" id="EndDateHidden"></input> <!-- this is used so we can post the end date to $_POST -->
</td>
</tr>
<tr> <!-- Next > -->
<td style="vertical-align:top" width="500px" bgcolor="lightgray"><descriptive></descriptive></td>
<td width="500px" bgcolor="lightgray" align="right"><input type="submit" value="Next"></input></td>
</tr>
</table>
</form>
</body>
A simple example for a standard pattern to follow would be really useful.
I suggest you use $_SESSION to hold state between your forms, below is a very crude example, with 1 field on the first form which if good (numeric) , the entire form state is set into the session, then redirects to the second form to fill out additional fields. Very simple but you get the idea.
dataentry1.php
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// define form state
$form = [
'value' => $_POST,
'error' => []
];
// validate a_field
if (empty($form['value']['a_field'])) {
$form['error']['a_field'] = 'a_field is a required field!';
} elseif (!is_numeric($form['value']['a_field'])) {
$form['error']['a_field'] = 'a_field should be a number!';
}
// all good
if (empty($form['error'])) {
$_SESSION['form'] = $form;
exit(header('Location: dataentry2.php'));
}
}
?>
<?= (!empty($form['error']['global']) ? $form['error']['global'] : null) ?>
<form action="/dataentry1.php" method="post">
<lable>a_field:</lable>
<input type="text" name="a_field" value="<?= (isset($form['value']['a_field']) ? htmlentities($form['value']['a_field']) : null) ?>">
<?= (!empty($form['error']['a_field']) ? '<br>'.$form['error']['a_field'] : null) ?>
<br>
<input type="submit" value="Submit">
</form>
dataentry2.php - requires the previous form to be filled out.
<?php
session_start();
// set form into scope from session
if (!empty($_SESSION['form'])) {
$form = $_SESSION['form'];
} else {
$_SESSION['form']['error']['global'] = 'You must fill out dataentry1 form first';
exit(header('Location: dataentry1.php'));
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// define form state
$form = [
'value' => array_merge($form['value'], $_POST),
'error' => []
];
// validate a_field
if (empty($form['value']['b_field'])) {
$form['error']['b_field'] = 'b_field is a required field!';
} elseif (!is_numeric($form['value']['b_field'])) {
$form['error']['b_field'] = 'b_field should be a number!';
}
// all good
if (empty($form['error'])) {
exit('Do something cool!');
}
}
?>
<form action="/dataentry2.php" method="post">
<lable>a_field:</lable>
<input type="text" name="a_field" value="<?= (isset($form['value']['a_field']) ? htmlentities($form['value']['a_field']) : null) ?>" readonly="readonly">
<?= (!empty($form['error']['a_field']) ? '<br>'.$form['error']['a_field'] : null) ?>
<lable>b_field:</lable>
<input type="text" name="b_field" value="<?= (isset($form['value']['b_field']) ? htmlentities($form['value']['b_field']) : null) ?>">
<?= (!empty($form['error']['b_field']) ? '<br>'.$form['error']['b_field'] : null) ?>
<br>
<input type="submit" value="Submit">
</form>
I am writing the code for a simple website where users log in and out and some other basic functions. I would like it to be so when anyone logs in, a logout button is shown on all the pages they visit, and hidden if they are not logged it. I am still new and cannot figure out what is wrong. The logout button appears as soon as i initially click the login button, but when i navigate to other pages the button disappears from my menu.
menu.php
$currentfile = basename($_SERVER['PHP_SELF']);
if($currentfile = basename($_SERVER['PHP_SELF'])){
if (isset($_SESSION['ID'])) {
echo "Home
See Reviews
Write a Review
Search
<a href='logoutconfirmation.php'>Logout</a>
<hr />";
}else{
echo "Home
See Reviews
Write a Review
Search
<hr />";
}
} ?>
index.php
<?php
include "header.inc.php";
$pagetitle= "Login Form";
$showform =1;
$errormsg =0;
$errorusername = $errorpassword = "";
$inputdate = time();
//FIRST CHECK TO SEE IF THE USER IS LOGGED IN
if(isset($_SESSION['ID']))
{
echo "<p class='error'> You are already logged in. </p>";
include_once "footer.inc.php";
exit();
}
if(isset ($_POST['submit'])) {
/*************************************************************
* ALL FIELDS- STORE USER DATA; SANITIZE USER-ENTERED DATA
*************************************************************/
$formfield['username'] = trim($_POST['username']);
$formfield['password'] = trim($_POST['password']);
if (empty($formfield['username'])) {
$errorusername = "The username is required.";
$errormsg = 1;
}
if (empty($formfield['password'])) {
$errorpassword = "The password is required.";
$errormsg = 1;
}
if ($errormsg != 0) {
echo "<p class='error'> THERE ARE ERRORS!</p>";
} else {
//get the user data from the database
try {
$user = "SELECT * FROM Users WHERE username =:username";
$stmt = $pdo->prepare($user);
$stmt->bindValue(':username', $formfield['username']);
$stmt->execute();
$row = $stmt->fetch();
$countuser = $stmt->rowCount();
// if query okay, see if there is a result
if ($countuser < 1) {
echo "<p class='error'> *This user cannot be found in the
database* </p>";
} else {
if (password_verify($formfield['password'], $row['password'])) {
$_SESSION['ID'] = $row['ID'];
$showform = 0;
header("LocationL confirm.php?state=2");
echo "<p> Thank you for logging in! </p>";
} else {
echo "<p class='error'> The username and password
combinations you entered are not correct. Please try again! </p>";
}
}//username exists
} catch (PDOException $e) {
echo 'ERROR fetching users: ' . $e->getMessage();
exit();
}
}
}
if($showform == 1) {
?>
<p class="homemsg">Welcome to the Movie Review Hub! Feel free to look
around or sign in to write your own review.</p>
<form name="login" id="login" method="post" action="index.php">
<table class="center">
<tr>
<th><label for="username">Username: </label></th>
<td><input name="username" id="username" type="text" placeholder="Required Username"
}?><span class="error" <?php if (isset($errorusername)) {
echo $errorusername;
} ?></span></td>
</tr>
<tr>
<th><label for="password">Password: </label></th>
<td><input name="password" id="password" type="password" placeholder="Required Password"
}?><span class="error"> <?php if (isset($errorpassword)) {
echo $errorpassword;
} ?></span></td>
<tr>
<th><label for="submit">Submit: </label></th>
<td><input type="submit" name="submit" id="submit" value="submit"/></td>
</tr>
</table>
<p><a href=index.php>Register.</a></p>
<?php
include_once "footer.inc.php";
}
?>
Like I said i would like the logout button to be show on all of the pages if someone logs in from the index page, the menu is included in all of my files
The logout button initially shows when i press the login button, but when i refresh the page or navigate to another page it goes away.
Like #CBroe mention, try add session_start at start of every page.
Better create config file, put it there and include everywhere.
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 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
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