How to POST multiple pages of same data - javascript

first page was registration.php
on pay.php
<form action="success.php" method="post">
<input type="hidden" value=<?php echo json_encode($_POST); ?> custom="Hidden Element" name="customer">
</form>
on success.php
I am not getting any values
<?php
$_POST['customer'] = json_decode($_POST['customer'],true);
echo $_POST['customer']['name']; //prints nothing
?>

Instead of passing your data back to the frontend, create a session on the server in which your data is temporarily stored across all pages.
When a session is started you can access and set your values by using the $_SESSION global variable. This variable is available across all of your files once a session is started and will hold hold your values until the session ends.
// Check if there is an active session.
// Otherwise start it.
if ( ! session_id() ) {
session_start();
}
// Receive and store.
$customer = $_POST[ 'customer' ]
$_SESSION[ 'customer' ] = $customer;
// Just to show what is in the session.
echo json_decode( $_SESSION[ 'customer' ] );
And if you're finished and you want to end the session on the last page then use session_destroy() to remove the entire session. Another option is to just let the session timeout and remove itself.

<?php
$data = ["name"=>"Thomas O'Leary"];
$encoded = json_encode($data);
//$encoded = bin2hex($encoded);
var_dump($_POST);
if(isset($_POST['data'])) {
$data = $_POST['data'];
//$data = hex2bin($data);
$data = json_decode($data, true);
var_dump($data);
}
?>
<form method='post'>
<input type='hidden' name='data' value='<?= $encoded ?>'>
<input type='submit'>
</form>
Upon form submission, you'll get this output:
array(1) { ["data"]=> string(17) "{"name":"Thomas O" } NULL
Indicating data loss, and invalid json.
This is because of the quotes in the hidden field value:
<input type='hidden' name='data' value='{"name":"Thomas O'Leary"}'>
If you use double quotes for the attribute, you can imagine also running into issues.
So the quotes need some kind of escaping/encoding.
If you uncomment the bin2hex and hex2bin lines above, you'll get the output:
array(1) { ["data"]=> string(50) "7b226e616d65223a2254686f6d6173204f274c65617279227d" } array(1) { ["name"]=> string(14) "Thomas O'Leary" }
Some use htmlentities($data, ENT_QUOTES); or base64_encode($data) as another workaround.

Related

Passing a PHP variable with fetched data to a JavaScript variable returns NULL or empty

I have an issue with returning the value of a PHP variable in JS. It returns NULL or empty instead of returning the age.
Approach:
Passing PHP variable with data to a JS variable in a separate file. Display JS variable in an alert(). Data was fetched from the database using fetch_assoc() in a while loop. Without using Ajax!
Proposed plan:
Enter a name.
Submit.
PHP fetches the age associated with that name.
age is stored in a PHP variable dbage.
Passed into JS variable to alert user what their age is.
I am trying to pass $dbage from sampletest.php to user in sample.php which will onsubmit display an alert saying: "Your age is blah".
blah is $dbage, which contains the age. This is for testing. Once I understand why this isn't working, I can move on to sending these JS variables to functions that will do calculations and return back to the DB.
What I have tried so far..
Trying to catch echo using ob_start() but that returned NULL as well.
Example:
ob_start();
echo $dbage;
$output = ob_get_contents();
ob_end_clean();
Making $dbage a global variable. Returns empty.
Echo variable outside the while loop but that returned NULL.
Example:
$dbage = '';
while( $row = $result->fetch_assoc()) {
$dbage = $row['age'];
}
echo $dbage;
Any suggestions, corrections are appreciated.
sample.php (index file)
<?php
include 'sampletest.php';
session_start();
?>
<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<body>
<div id="id03">
<form class="modal-content" action="sampletest.php" method="post" onsubmit="myFunction()">
<div class="container">
<input type="text" id="name" placeholder="Enter name" name="name">
<div class="clearfix">
<button type="submit" class="loggedinbtn" name="load"/>Load
</div>
</div>
</form>
</div>
<script>
function myFunction() {
var user = '<?php echo(json_encode($dbage)); ?>';
alert("This is a php varible " + user);
}
</script>
</body>
</html>
sampletest.php
if(isset($_POST['load'])){
require 'config.php';
$name = $_POST['name'];
$age = $_POST['age'];
if(empty($name)) {
echo "Enter a number";
}elseif(!preg_match('/^[a-z ]+$/i', $name)){
echo "Enter a letter, no numbers";
}else{
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
header("location: sample.php?Connect-database=failed");
exit();
}
$sql = "SELECT name, age FROM results WHERE name= '$name';";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while( $row = $result->fetch_assoc()) {
$dbage = $row['age'];
}
}
else{
echo "0 results";
}
$conn->close();
}
}
your action in the form should be set to sample.php, i think is the first problem. then get rid of the javascript all together.
<form class="modal-content" action="sample.php" method="post">
then change:
<script>
function myFunction() {
var user = '<?php echo(json_encode($dbage)); ?>';
alert("This is a php varible " + user);
}
</script>
to just
<script>
var user = <?php echo $dbage; ?>;
alert("This is a php varible " + user);
</script>
submitting html forms to PHP does not require javascript at all.
From what I can see is that the actual query that you're sending is { name= '$name' }, try { name=' " . $name . " ' }.

Retrieving JSON Object after new page load

I am not familiar with JSON handling in a web dev context, so would appreciate a little guidance.
I have a login utilising a web form - if a successful login has been made, a JSON array is returned as follows:
{
"result": "success",
"message": "Login Successful",
"user": {
"name": "Foo Bar",
"email": "foo#bar.com",
"unique_id": "59bea8b7d56a63.8888888"
}
}
My DB Operations returns the JSON to my Functions.PHP. I then do the following:
$response["result"] = "success";
$response["message"] = "Login Successful";
$response["user"] = $result;
$json = json_encode($response);
It's here that I am stuck because I want to send the encoded JSON to the web page that will be open on success, as I want to make further DB queries based on the user unique_id.
I have tried on page 1:
$response["result"] = "success";
$response["message"] = "Login Successful";
$response["user"] = $result;
$json = json_encode($response);
header('Location: http://example.co.uk/quiz/dashboard.php/'.$json);
Page 2
<?php
$data_get = $_REQUEST['user'];
?>
<script type="text/javascript">
var mydata =<?php echo $data_get; ?>;
</script>
But I have not been able to echo out the user data. I want to be able to retrieve the encoded array on page 2 and then decode it and store the name/email/unique_id in variables to use when needed on page 2.
You line:
header('Location: http://example.co.uk/quiz/dashboard.php/'.$json);
seams to be the problem.
If you really want to transfer the whole json string via GET request you need to define a name for it. try this:
header('Location: http://example.co.uk/quiz/dashboard.php?data='.$json);
And then on page 2 this is how you receive it:
$response = json_decode($_GET['data']);
After that you can access the $response array same as on page 1.
Btw: it might be easier to store the data in a session.
In your page 1
$response["result"] = "success";
$response["message"] = "Login Successful";
$response["user"] = $result;
$json = json_encode($response);
header('Location: http://example.co.uk/quiz/dashboard.php/?data='.$json);
In Page 2 you will get values like that
$data = json_decode($_GET['data']);
echo $data->message. "</br>";
echo $data->result."</br>";
echo $data->user."</br>";
Or if you want assign json to javascript variable then
<script type="text/javascript">
var mydata =<?php echo $_GET['data']; ?>;
</script>
With what you are doing try this in file 2:
$decoded=json_decode(array_keys($_REQUEST)[0]);
echo $decoded->user;

PHP doesn't output error from mysql query for non-existent rows for autocomplete

I have a form that currently is able to auto complete base on user input, it queries the MySQL database and successfully lists all possible matches in the table and give suggestions. Now I want to handle rows that do not exist. I am having trouble to get my PHP file to echo the error. Here is what I have so far:
I'm guessing in my auto search function in my javascript in main.php I need to return the error message to the page?
search.php
<?php
//database configuration
$host = 'user';
$username = 'user';
$password = 'pwd';
$name = 'name';
//connect with the database
$dbConnection = new mysqli($host,$username,$password,$name);
if(isset($_GET['term'])){
//get search term
$searchTerm = '%'.$_GET['term'].'%';
//get matched data from skills table
if($query = $dbConnection->prepare("SELECT * FROM nametbl WHERE name LIKE ? ORDER BY name ASC")) {
$query->bind_param("s", $searchTerm);
$query->execute();
$result = $query->get_result();
//$row_cnt = $result->num_rows;
//echo $row_cnt;
if($result -> num_rows){
while ($row = $result->fetch_assoc()) {
$data[] = $row['name'];
}
//return json data
echo json_encode($data);
mysqli_close($dbConnection);
}
else { echo '<pre>' . "there are no rows." . '</pre>'; }
}
else {
echo '<pre>' . "something went wrong when trying to connect to the database." . '</pre>';
}
}
?>
main.php
<div id="gatewayInput">
<form method="post">
<input type="text" id="name" name="name" placeholder="Name..."><br><br>
<?php
include("search.php");
?>
</div>
...
...
...
<script src ="../../../jqueryDir/jquery-3.2.1.min.js"></script>
<script src ="../../../jqueryDir/jquery-ui.min.js"></script>
<script type="text/javascript">
//auto search function
$(function() {
$( "#name" ).autocomplete({
source: 'search.php'
});
});
1.your method type is post in the form
in main.php
and in the search.php, you have used "if(isset($_GET['term'])){"
this needs to be fixed I guess. either both needs to be POST or GET.
Again you are using include method which the whole code in search.php will be made in-line and treated as a one file main.php. so you need not use GET or Post method.
How does get and Post methods work is
3.1) you have a html or PHP which submits the data from browser(main.php), and this request is being served by an action class(search.php)
example :- in main.php
3.2) now in search.php you can use something like if(isset($_POST['term'])){
You can use num_rows (e.g. if ($result -> num_rows)) to see if the query returned anything.

AJAX does not POST results to php page

I'm trying to create a player edit system for an admin section of a football website. The process goes as follows:
Once a coach has logged in on 'coaches.php', they can then choose what coaching session they want to look at via dropdown, which then populates the 'player' dropdown (done via js below)
form on coach-home.php
<form id="form1" name="form1" method="post" action="coach-player.php">
<label>Activity :</label>
<select name="activity" class="activity">
<option selected="selected">--Select Activity Group--</option>
<?php
include('dbconnect.php');
$sql=mysql_query("select activity from coaches where username='$coach'");
while($row=mysql_fetch_array($sql))
{
$activity2=explode(",",$row["activity"]);
foreach ($activity2 as $activity)
echo '<option value="'.$activity.'">'.$activity.'</option>';
} ?>
</select> <br/><br/>
<label>Player :</label> <select name="username" class="username">
<option selected="selected">--Select Player--</option>
</select>
<input type="text" name="pid" class="pid" id="pid" value="<?php echo $pid; ?>" />
<input type="submit" name="button" id="button" value="Log In" />
</form>
JS request on coach-home.php
<script type="text/javascript">
$(document).ready(function()
{
$(".activity").click(function()
{
var activity=$(this).val();
var dataString = 'activity='+ activity;
$.ajax
({
type: "GET",
url: "username.php",
data: dataString,
cache: true,
success: function(html)
{
$(".username").html(html);
}
});
});
});
</script>
username.php
<?php
if($_GET['activity'])
{
$activity=$_GET['activity'];
$sql=mysql_query("SELECT pid, username FROM stats WHERE activity='$activity'");
while($row=mysql_fetch_array($sql))
{
$pid=$row['pid'];
$username=$row['username'];
echo '<option value="'.$username.'">'.$username.'</option>';
}
}
?>
Once all of this is done, the coach submits the form, taking them to coachplayer.php. This is where the problem begins.
coachplayer.php is a template page, with empty fields filled with echo's, to echo the player details where necessary. A query runs to get the id of the selected player, bring up their details and fill the page. Instead, however, it echos what usually comes up if the query cannot find a matching result via $playerCount as shown below, saying "Player doesn't exist".
coach-player.php Query
<?php
// Check to see the URL variable is set and that it exists in the database
if (isset($_GET['username'])) {
// Connect to the MySQL database
$puser = preg_replace('#[^0-9]#i', '', $_GET['username']);
// Use this var to check to see if this ID exists, if yes then get the product
// details, if no then exit this script and give message why
$sql = mysql_query("SELECT * FROM stats WHERE username='$puser' LIMIT 1");
$productCount = mysql_num_rows($sql); // count the output amount
if ($productCount > 0) {
// get all the product details
while($row = mysql_fetch_array($sql)){
$username = $row["username"];
$pid = $row["pid"];
$position = $row["position"];
$activity = $row["activity"];
$agegroup = $row["agegroup"];
$goals = $row["goals"];
$assists = $row["assists"];
$cleans = $row["cleans"];
$motm = $row["motm"];
}
} else {
echo "That player does not exist.";
exit();
}
} else {
echo "Data to render this page is missing.";
exit();
}
?>
The issue here is that whilst it is defined in username.php, the pid does not get sent over and saved when the rest of the form on coach-home sends. I have tried changing from GET to POST with no avail. I have also just tried using the 'username' instead of 'pid' but I get "That player does not exist."; - meaning no variables outside of the ajax request is sending.
What is it that needs to be altered to save and post the data mentioned?
Looking at your code the $username and $pid variables are not being passed to either coach-home.php or coach-player.php, thus when you try to write to the database the parameter $_GET['username'] or $_GET['pid'] is set (because you have provided an input field in your form), but it has no value! and thus there is no player that exists with an empty pid or username.
Also note that in the form you have specified the method as post, but in the php you are referencing the get hash. If you submit by post you access variables with $_POST, submit with get you access with $_GET.
My suggestion is to use the session hash to store the username and pid of the user.
When the user logs in:
$_SESSION['username'] = 'jonnysmith'
$_SESSION['pid'] = '45'
This will mean when you initiate the database query you will just reference the session value instead of the get value for the parameter.
Delete your input field for username/pid in the form.
Call session_start(); in your config.php file to enable the session hash.
Call session_destroy(); when the user logs out to clear the session hash.
Also you will need to logout and log back in for the changes to take effect and the value of username/pid to be stored in the session hash.
Happy hunting!
Your regex is actually replacing your whole username variable with ''
Based on your comment, I've done a test match with the name 'Radamel Falcao' and echo-ed $puser and I got empty string, so apparently, this regex is your problem.
$puser = preg_replace('#[^0-9]#i', '', $_GET['username']);

Store random string in Session, which gets overwritten, when I call it through another PHP-File

I created a form, which includes an hidden input and its value is set by an function.
<?php
class Token {
public static function generate(){
return $_SESSION['token'] = base64_encode(openssl_random_pseudo_bytes(32));
}
}
?>
This is called like this:
<input type="hidden" id="token" value="<?php echo Token::generate(); ?>">
I sent it via JavaScript/AJAX to another file (e.g. "form.php"), which contains something like:
<?php
session_start();
#require_once 'Token.class.php';
echo $_POST['token'] . " => " . $_SESSION['token']; // different tokens, why?
// $_POST['token'] is the one, that I want
// and so on...
?>
Why do the values change, when I type in: <?php echo $_SESSION['token']; ?> ?
This is my project stored on Dropbox
Because you are generating new one every time you are entering a site?
<?php
class Token {
public static function generate(){
if(isset($_SESSION['token']) && $_SESSION['token']) return $_SESSION['token'];
else return $_SESSION['token'] = base64_encode(openssl_random_pseudo_bytes(32));
}
}
?>
PS. You may want to use md5(uniqid()) instead.

Categories