Cannot pass form data to database (PHP, Jquery) - javascript

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

Related

Unable to set PHP variables as values for input field in form

I have a PHP file which SELECT's all from the row found based on an SQL query. When I put the echo in a div, I get all information, but when I try to echo it into an input box in a form, it does not shows.
What am I doing wrong?
Please also note that I am aware that I am (most likely) making a lot of mistakes when it comes to security practices or programming standards, but this whole thing (PHPDesktop > https://github.com/cztomczak/phpdesktop) will get packed into an EXE file which will run locally only (no need for an online connection as the SQLite3 DB gets packed in with the EXE), and I am still figuring out how to program this in the first place, so efficient and tidy coding are not high on my list yet ;-)
DO_CUSTEDIT.PHP
$custName = $_POST['custName'];
$query = "SELECT * FROM `CustDB` WHERE CustName LIKE '%$custName%'";
$result = $db->query($query);
while ($row = $result->fetchArray()) {
$custID = $row['CustID'];
......;
}
if (!$result) {
echo $db->lastErrorMsg();
$db->close();
exit;
} else {
echo $custID;
echo ......;
$db->close();
exit;
}
EDITCUST.PHP / Javascipt
<script>
$(document).ready(function() {
$("#subeditcust").on('click',function(e) {
e.preventDefault();
$.ajax( {
url: "lib/do_editcust.php",
method: "post",
data: $("form").serialize(),
dataType: "text",
success: function(strMessage) {
if (strMessage == "Customer updated successfully") {
$("#message").text(strMessage);
$("#neweditform").get(0).reset();
} else {
$("#message").text(strMessage);
}
}
});
});
});
</script>
EDITCUST.PHP / HTML
<form id="editcustform" name="editcustform" action="" method="post">
<div class="row">
<div class="column-half" style="background-color:#fff">
<table>
<tr>
<td>
<a>Customer ID</a>
</td>
<td>
<div class="inputb">
<input type="text" name="custID" value="<?php echo (isset($custID)) ? $custID: ''; ?>" readonly/>
</div>
</td>
</tr>
</table>
</div>
</div>
<div class="row">
<table style="table-layout:fixed">
<td style="background-color: rgb(215,215,215); padding:0 10px;">
<button id="subeditcust" type="submit" class="mainbtn">Create</button>
</td>
<td style="background-color: rgb(215,215,215); padding:0 10px;">
<button id="reseteditcust" type="reset" class="mainbtn">Reset</button>
</td>
</table>
</div>
</form>
<input type="text" name="custID" value="<?php echo (isset($custID) ? $custID: ''); ?>" readonly/>
Replace this line with yours it will work. IA
It seems you have two different files, right? DO_CUSTEDIT.PHP and EDITCUST.PHP
The variables are being created on DO_CUSTEDIT.PHP and the when you are creating the HTML code those variables ($custID) are not setted.
Is one file including or requiring the other?
EDITCUST.PHP is your first page from you are submitting form to DO_CUSTEDIT.PHP
When you land on EDITCUST.PHP variable $custID is not created
When the form is submitted through ajax, the ajax returns the data inform of object or array depending on how you are echoing the data from DO_CUSTEDIT.PHP
I would recommend to use json_encode() php function to return inform of array
To debug the value by logging the data in console (though function console.log())
After returning the value from ajax, you have to populate the value in form through jquery something like $(input[name="custID"]).val( data.custID )
I managed to figure it out!
DO_CUSTEDIT.php / PHP
$results = array($custID, $custName);
echo json_encode($results, JSON_PRETTY_PRINT);
EDITCUST.php / HTML
<input type="text" id="custID" name="custID" value="" readonly/>
<input type="text" id="custName" name="custName" value="" readonly/>
EDITCUST.php / JS
<script>
$(document).ready(function() {
$("#subeditcust").on('click',function(e) {
e.preventDefault();
$.ajax( {
url: "lib/do_editcust.php",
method: "post",
data: $("form").serialize(),
dataType: 'json',
success: function(data){
document.getElementById('custID').value = data[0];
document.getElementById('custName').value = data[1];
}
});
});
});
</script>

PHP programmatically navigate to new form using post [duplicate]

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>

My form is not sending data correctly using Ajax, how can I fix it?

I want to send the data that is in the form to my database using Ajax and depending on the action of the button it will execute the url I need, but It doesn't seem to be working because It only sends zero like as if the form were completely empty
HTML
<form method="post" id="form_shirt" enctype="multipart/form-data">
ID:
<br>
<input type="hidden" name="id_shirt" id="id_shirt" class="form-control"> Name:
<br>
<input type="text" name="name_shirt" id="name_shirt" class="form-control" required="required"> Price:
<br>
<input type="text" name="price_shirt" id="price_shirt" class="form-control" required="required">
<button id="insert_shirt" class="submit" name="btninsert" id="btninsert" value="Insert" />
<button id="update_shirt" class="submit" name="btnupdate" id="btnupdate" value="Update" />
<button id="delete_shirt" class="submit" name="btndelete" id="btndelete" value="Delete" />
</form>
JavaScript
$(document).ready(function() {
$('.submit').on("click", function() {
$.ajax({
url: this.id + ".php",
method: "POST",
data: $('#form_shirt').serialize(),
contentType: false,
cache: false,
processData: false,
success: function(data) {
$('#form_shirt)[0].reset();
$('#table_shirt').html(data);
}
});
});
});
PHP
<?php
$connect = mysqli_connect("localhost", "root", "", "shirts");
$output = '';
$name_shirt = mysqli_real_escape_string($connect, $_POST["name_shirt"]);
$price_shirt = mysqli_real_escape_string($connect, $_POST["price_shirt"]);
$query = "INSERT into shirts ( name, price)
VALUES ('$name_shirt','$price_shirt') ";
if(mysqli_query($connect, $query))
{
$output .= '<label class="text-success">Data Inserted</label>';
$select_query = "SELECT id_shirt, name, price FROM shirts";
$result = mysqli_query($connect, $select_query);
$output .= '
<table id="shirts" class="table table-bordered">
<thead>
<tr>
<th>ID</th>
<th>NAME</th>
<th>PRICE</th>
</tr>
</thead>
';
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<tbody>
<td>' . $row["id_shirt"] . '</td>
<td>' . $row["name"] . '</td>
<td>' . $row["price"] . '</td>
</tr>
</tbody>
';
}
$output .= '</table>';
}
echo $output;
?>
Are you aware that all your buttons have their id declared twice?
<button id="insert_shirt" class="submit" name="btninsert" id="btninsert" value="Insert" />
This may very well be the cause for your misfire, because it will try to POST to a URL that doesn't exist, returning an empty value.
Also, buttons have both opening and closing tags.
I think the line below should be sufficient for your goal:
<button type="button" id="insert_shirt" class="submit">Insert</button>
I added type="button". If you don't declare a type, the browser will choose for you, and since the button is inside a form, it will probably become type="submit", which you don't want because you're using Ajax.
In the codepen below I didn't add a type, and as you can see the form is submitted when you click one of the buttons.
I removed both name="btninsert" and value="Insert", I assume you don't use the value in you PHP script, which probably means you also don't need the name.
Check this pen to see it in action: https://codepen.io/anon/pen/MoNXYj?editors=1010
(You can actually use the buttons, CodePen will simulate the submit action for you)
UPDATE
This may be a bit naive and/or ignorant of me, but if you're still having problems a simpler solution might be to change your set-up a bit so that all elements and code work in the same form-submitting-type-direction. You are now using elements for sync submitting and counteracting that with code for async submitting.
HTML:
<div id="form_shirt">
<input type="hidden" name="id_shirt" id="id_shirt" class="form-control"><br>
Name: <input type="text" name="name_shirt" id="name_shirt" class="form-control" required="required"><br>
Price: <input type="text" name="price_shirt" id="price_shirt" class="form-control" required="required">
<br><br>
<button type="button" id="insert_shirt" class="submit">Insert</button>
<button type="button" id="update_shirt" class="submit">Update</button>
<button type="button" id="delete_shirt" class="submit">Delete</button>
</div>
JS:
$(document).ready(function() {
$('.submit').on("click",function() {
$.post(this.id+".php", {
id_shirt: $('#id_shirt').val(),
name_shirt: $('#name_shirt').val(),
price_shirt: $('#price_shirt').val()
}, function(data) {
$('#form_shirt .form-control').val("");
$('#table_shirt').html(data);
});
});
});
codepen: https://codepen.io/anon/pen/bRXKaV?editors=1011
(Note that this will not produce any output, because there is no form submitted, only the Ajax POST to a URL that doesn't exist and therefor doesn't return a response)

How can fill the form and return back to modify the records in php

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.

Recaptcha alert incorrect on same page

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.
}

Categories