Locate the reasoning for NULL values between HTML and PHP - javascript

I am trying to figure out why the resulting values are...
NULL NULL string(4) "PEAR"
..on the page they are displayed on.
Originally I do not want them to be displayed but I want the php code to run, using local storage data, when the page loads, then possibly return a boolean value or something in that direction. With a set goal in mind, I am looking for the mistake I have made that creates the NULL values. I have the following code:
validateSession.php , php functionality that will validate values from localstorage and database
<?php
include("config.php");
include("refc/refcvalidation.php");
$sesuserid = $_POST[$valuserid];
$sessionid = $_POST[$valsesid];
var_dump($sesuserid, $sessionid);
$conn = new mysqli($dbservername, $dbusername, $dbpassword, $dbname) or die($conn);
$stmt = $conn->prepare("SELECT * FROM sessiontable WHERE sesowner=? AND sescode=?");
$stmt->bind_param("is", $sesuserid, $sessionid);
$stmt->execute();
$result = $stmt->get_result();
$conn->close();
if ($result->num_rows > 0) {
var_dump("APPLES");
}else{
var_dump("PEAR");
}
?>
refcvalidation.php , reference coordination, ensuring same value on both pages
<?php
$valuserid = "VALSES1";
$valsesid = "VALSES2";
?>
homepage.php , basic page with contents
<?php
include("services/refc/refcvalidation.php");
include('services/validateSession.php');
?>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
<link rel="stylesheet" href="general/styling.css">
<script src="general/launch.js"></script>
</head>
<body>
<div id="topBox">
</div>
<div class="box">
<form id="logForm" action="validateSession.php" method="post">
<input type="hidden" required="required" name="<?php echo $valuserid ?>" id="userfield">
<input type="hidden" required="required" name="<?php echo $valsesid ?>" id="sesidfield">
</form>
</div>
</body>
<style>
</style>
</html>
<script>
document.getElementById("userfield").value = localStorage.getItem("userid");
document.getElementById("sesidfield").value = localStorage.getItem("sessionid");
</script>
The values within HTML are set and have a value in the script section, they are null within the PHP $_POST[$valuserid]; and $_POST[$valsesid]; . Any ideas?

Have'nt tested this, but it might give you some ideas to a solution.
Maybe we could impolement some Ajax into this?
What is Ajax?
AJAX = Asynchronous JavaScript and XML. AJAX is a technique for creating fast and dynamic web pages. AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page. Ajax can give data as response.
refcvalidation.php
This should be removed
validateSession.php
<?php
include("config.php");
//include("refc/refcvalidation.php"); //REMOVED
$sesuserid = $_POST['valuserid'];
$sessionid = $_POST['valsesid'];
$conn = new mysqli($dbservername, $dbusername, $dbpassword, $dbname) or die($conn);
$stmt = $conn->prepare("SELECT * FROM sessiontable WHERE sesowner=? AND sescode=?");
$stmt->bind_param("is", $sesuserid, $sessionid);
$stmt->execute();
$result = $stmt->get_result();
$conn->close();
if ($result->num_rows > 0) {
$myObj->sesuserid = $sesuserid;
$myObj->sessionid = $sessionid;
$myJSON = json_encode($myObj);
echo $myJSON;
return true; //CONTAINS SOMETHING
}else{
return false; //CONTAINS NOTHING
}
?>
homepage.php
<?php
include("services/refc/refcvalidation.php");
include('services/validateSession.php');
?>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
<link rel="stylesheet" href="general/styling.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="general/launch.js"></script>
</head>
<body>
<div id="topBox">
</div>
<div class="box">
<form id="logForm" action="validateSession.php" method="post">
<input type="hidden" required="required" name="<?php echo $valuserid ?>" id="userfield">
<input type="hidden" required="required" name="<?php echo $valsesid ?>" id="sesidfield">
</form>
</div>
</body>
<style>
</style>
</html>
<script>
$.ajax({
url: 'validateSession.php',
method: 'POST',
data: { valuserid: '<?php echo $valsesid ?>', valsesid: '<?php echo $valsesid ?>'},
success: function(data) {
var data_json= JSON.parse(data);
console.log(data_sjon);
localStorage.userid = data_json[0];
localStorage.sesidfield = data_json[1];
document.getElementById("userfield").value = localStorage.getItem("userid");
document.getElementById("sesidfield").value = localStorage.getItem("sessionid");
}
})
</script>

Related

How to pass PHP variable value to html input box from external PHP file?

HTML FILE
<body>
<input type="text" id="name" class="form-control" name="name">
<label for="name">name</label>
<script type="text/javascript" src="PHPfile.php"></script>
</body>
Separate PHP FILE
I have done MySQL query, and I have query value in $row['name'].
How can I put this value in the HTML input box?
<?PHP
**some code here**
//value in $row['name']
//confirmed by echo $row['name'];
// now I want to pass this value to my HTML input box
echo "<script>
var name = <?php echo $row['name'] ?>;
document.getElementById(name).value='name';
window.location.href='htmlpage.html';
</script>";
?>
I tried this but this didn't work. I got the following error
Parse error: syntax error, unexpected string content "", expecting "-" or identifier or variable or number in...
I have tried to provide custom variable to var name and then document.getElementByID line. Still, it doesn't work.
Any Solution?
This should work.
<?php
/**some code here**/
//value in $row['name']
//confirmed by echo $row['name'];
// now I want to pass this value to my HTML input box
echo '<script>
document.getElementById("name").value = "' . $row['name'] . '";
</script>';
?>
or same thing if more complex HTML/script needed:
<?php
/**some code here**/
//value in $row['name']
//confirmed by echo $row['name'];
// now I want to pass this value to my HTML input box
?>
<script>
document.getElementById("name").value = "<?=$row['name'];?>";
</script>
<?php
/* more php code */
?>
If you still get the same error message, than the problem is somewhere else.
To echo a variable in a string ( in php ) we can use concatenation " . " $var['code'] ". " or template string { $var["code"] }
PHPfile.php
<?php
$row = ["name" => "something"];
echo "
let input = document.getElementById('name');
input.value = '{$row['name']}';
setTimeout(()=>{
window.location.href='htmlpage.html';
} ,2000)
"
?>
For echoing variables in string use {$var} instead of simple concatenation
Extended answer
index.php
<?php
// all querys here ... getting results from db
// assuming result
$row = [
"username" => "xxxxxxxxx",
"email" => "xxxxx#example.com"
];
$name = $row['username'];
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width , initial-scale=1.0">
<title>Damn Forms ! </title>
</head>
<body>
<form action="file.php" method="post" accept-charset="utf-8">
<label for="name">Name <span class="red">*</span></label>
<input type="text" id="name" class="form-control" name="name" placeholder="Enter your full name " value="<?= $name ?>">
<!-- sending values to another php file -->
<button type="submit">Submit</button>
</form>
</body>
</html>
file.php
<?php
if($_SERVER["REQUEST_METHOD"] === "POST"){
$name = $_POST['name'];
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width">
<title>Input Form </title>
</head>
<body>
<input type="text" name="name" id="" value="<?= $name ?>" />
</body>
</html>
I see 2 answers already, but my way of doing it would be....
HTML
<body>
<input type="text" id="name" class="form-control" name="name">
<label for="name">name</label>
<div id="externalPHP"></div>
<script type="text/javascript">
document.getElementById("externalPHP").innerHTML='<object type="type/php" data="PHPfile.php" ></object>';//javascript
$('#externalPHP').load('PHPfile.php');//jQuery
</script>
</body>
The php file
<?PHP
**some code here**
//value in $row['name']
//confirmed by echo $row['name'];
// now I want to pass this value to my HTML input box
echo '<script>document.getElementById("name").value='."$row['name']".';</script>';
?>

Using javascript/jQuery to populate a form field with database value

I have a PHP form used to submit data. This form auto-populates fields based on a case number or "id" by querying a SQL database and retrieving more data to populate other fields based on the ID. I am tasked with adding a field, but I cannot get it to auto-populate. I tried reverse-engineering the other fields, but this thing is like a spider web.
The goal is to query for a date field in the SQL DB, pull that date, and input it into the text field in the main form's #3. "PMV to MVA" input/text field.
I have redacted irrelevant code for simplicity's sake:
recoveryForm.php (the main form): User enters case number, and using the onblur="loadCase()" function, the fun begins..
<html>
<head>
<meta charset="UTF-8">
<title>Recovery Form</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<script src="jquery-3.3.1.min.js"></script>
<script src="recoveryForm.js"></script>
</head>
<body>
<div class="borderdiv"><div class="innerdiv">
<h1>Recovery Template:</h1>
<p>Date: <?php echo date("Y-m-d H:i:s"); ?></p>
<form action="submit_1.php" id="mainForm" method="post">
<p>
<span class="qText" name="casenum"><b>Case Number: </b></span>
<input type="number" name="casenum_a" onblur="loadCase();" required>
</p>
<table class="mainTable" name="mainTable">
<tr>
<td><span class="qText" name="pmv_to_mva">3. PMV to MVA:</span></td>
<td><span class="qAns" name="pmv_to_mva_a">No</span></td>
</tr>
</table>
<div class="submitDiv"><input type="submit" value="Submit Form"></div>
</body>
</html>
recoveryForm.js: which contains all of the JS functions
function loadCase(){
getPMV();
document.getElementsByName("casenum1_s")[0].innerHTML=document.getElementsByName("casenum_a")[0].value;
function getPMV(){
var myCasenum=document.getElementsByName("casenum_a")[0].value;
window.alert(casenum_a);
$.post(
"getPMV.php",
{casenum: myCasenum},
function(data, status){ setPMV(data);}
);
}
function setPMV(data){
var jdata=JSON.parse(data);
document.getElementsByName("pmv_to_mva_a")[0].value=jdata.ptm;
document.getElementsByName("pmv_to_mva_a")[0].innerHTML=jdata.ptm;
}
And the getPMV.php file that's called from within the JS function:
<?php
$success=FALSE;
$postCasenum = getPostCasenum();
#header('Content-Type: application/json');
$sql = "select user_case_data.PMV_to_MVA from user_case_data WHERE casenum=?";
$conn = odbc_connect( "needles","dba","sql" );
if( $conn ) {
echo $sql;
$stmt=odbc_prepare($conn, $sql);
$queryResult=odbc_execute($stmt);
if (odbc_fetch_row($stmt)) {
$data = [
'ptm' => odbc_result($stmt,1) ? "No" : "Yes"
];
echo json_encode($data);
odbc_close( $conn );
} else {
echo "{}";
}
?>
<?php
function getPostCasenum(){
return $_POST["casenum"];
}
?>
I know the SQL query is good and returns the date value I want to update onto the form. I put the javascript inline in the last code example on this page that can be used as an example (along with jquery file and getPMV.php). No matter what I try, the json response shows blank/empty for the pmv_to_mva field, when I know that field does indeed contain data.
Anybody might be able to point me in the right direction here? Thank you.
========================== EDIT =================================
I continued to get "loadCase is not defined at HTMLInputElement.onblur", so I reasoned that there still must be some syntax error with my javascript. I decided to move the script inline to see if I could make any progress.
"Uncaught reference error: casenum_a is not defined at getPMV"...
recoveryform.php (line 16):
<input type="number" name="casenum_a" onblur="loadCase();" required>
recoveryForm.php in it's entirety:
<html>
<head>
<meta charset="UTF-8">
<title>Recovery Form</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<script src="jquery-3.3.1.min.js"></script>
<!--<script src="recoveryForm.js"></script>-->
<script type="text/javascript">
function loadCase(){
getPMV();
function getPMV(){
var myCasenum=document.getElementsByName("casenum_a")[0].value;
console.log(casenum_a);
$.post(
"getPMV.php",
{casenum: myCasenum},
function(data){ setPMV(data);}
);}
function setPMV(data){
console.log(data);
var jdata=JSON.parse(data);
document.getElementsByName("pmv_to_mva_a")[0].innerHTML=jdata.ptm;
}
}
</script>
</head>
<body>
<div class="borderdiv"><div class="innerdiv">
<h1>Recovery Template:</h1>
<p>Date: <?php echo date("Y-m-d H:i:s"); ?></p>
<form action="submit_1.php" id="mainForm" method="post">
<p>
<span class="qText" name="casenum"><b>Case Number: </b></span>
<input type="number" name="casenum_a" onblur="loadCase();" required>
</p>
<table class="mainTable" name="mainTable">
<tr>
<td><span class="qText" name="pmv_to_mva">3. PMV to MVA:</span></td>
<td><span class="qAns" name="pmv_to_mva_a">No</span></td>
</tr>
</table>
<div class="submitDiv"><input type="submit" value="Submit Form"></div>
</body>
</html>
Thank you everybody for all of your help and suggestions. I was able to accomplish what I was after. My problem was somewhere in my getPMV.php file. I found success in simplifying the file. This worked:
<?php
$success=FALSE;
$postCasenum = getPostCasenum();
header('Content-Type: application/json');
$sql = "select user_case_data.PMV_to_MVA from user_case_data WHERE casenum=?";
$conn = odbc_connect( "needles","dba","sql" );
if( $conn ) {
#echo $sql;
$stmt=odbc_prepare($conn, $sql);
$queryResult=odbc_execute($stmt, array($postCasenum));
$json='{';
while(odbc_fetch_row($stmt)){
$json=$json.'"ptm":"'.odbc_result($stmt,1).'"';
}
$json=$json.'}';
echo $json;
odbc_close( $conn );
} else {
echo "{}";
}
?>
<?php
function getPostCasenum(){
return $_POST["casenum"];
}
?>

I'm trying to create a live search bar on my webpage but can't seem to make it work. It just doesn't display any data

The template.php file contains all the coding related to the script.
<?php
include 'dbh.php';
?>
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<meta charset="UTF-8">
<title><?php echo $title; ?></title>
<link rel ='Stylesheet' type ='text/css' href ='Styles/StyleSheet.css'/>
</head>
<body>
<div id="banner">
</div>
<form action="">
<input type ="text" id="search">
</form>
<div id="result">
</div>
<div id="content_area">
<?php echo $content; ?>
</div>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#search').keyup(function()
{
var search = $('#search').val();
if($.trim(search.length)==0)
{
$('#result').html('Please enter correct data');
}
else
{
$.ajax({
type:'POST',
url:'Search.php',
data:{'search':search},
success:function(data)
{
$('#result').html(data);
}
});
}
})
})
</script>
</body>
</html>
The Search.php file contains the code related to query of data. My database has only one table named CINFO and has only one column named Title.
<?php
include 'dbh.php';
if(isset($_POST['search']))
{
$search = $_POST['search'];
$query = $db->prepare("SELECT * from CINFO where TITLE LIKE ?");
$query->execute(["%$search%"]);
$count = $query->rowCount();
if($count==0)
{
echo "Sorry No result found";
}
else
{
while($r = $query->fetch(PDO::FETCH_OBJ))
{
$name = $r->Title;
echo "$name";
}
}
}
?>
dbh.php has code related to the connection of the database-
<?php
$server = "localhost";
$username = "root";
$password = "root";
$dbname = "ComicDB";
$conn = mysqli_connect($server, $username, $password,$dbname);
?>
Whenever I enter any data in the search box, all it doesn't display any data but when I press backspace and delete what I've entered it does display 'Please enter correct data' which means the if block in template.php is getting executed but not the else block. Thats what I've understood out of the code. Can't seem to figure out what I've done wrong.

When I call my php script in another, Select js doesn't work

I have this code which works fine when ran standalone (I am able to search in the drop down list )
<?php
include_once ("db_connection.php");
$conn = testdb_connect ();
$sth = $conn->prepare('SELECT testCase FROM tooldata ');
$sth->execute();
while($row = $sth->fetch(PDO::FETCH_ASSOC))
{
foreach($row as $key)
{
$var=explode('_', $key);
$feature[] = $var[0];
}
}
$feature = array_intersect_key($feature, array_unique(array_map('strtolower', $feature)));
foreach($feature as $newarr)
{
$newFeature[]=$newarr;
}
?>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<link href="../select2-3.4.8/select2.css" rel="stylesheet"/>
<script src="../select2-3.4.8/select2.js"></script>
<script>
$(document).ready(function() { $("#feature").select2(); });
</script>
</head>
<body>
<h2>Select feature</h2>
<form method="get" action="feature.php">
<select name="feature" id="feature">
<?php
?>
<option value > Select Feature</option>
<?php
foreach($newFeature as $feat)
{
?>
<option value="<?php echo $feat;?>"><?php echo $feat;?></option>
<?php
}
?>
</select>
<input type="submit" name="submit" value="Feature">
</body>
</html>
When I include this script in other php script say main.php and when I run main.php my search in the drop down list does not work and I get this in my net tab - Uncaught TypeError: undefined is not a function for line 7 and 37 which are include("feature_list.php"); and } respectively.
what can be the possible reason for this ?
please guide

how do I display different content from database on one php file?

I am trying to use one php file php.project and depending on the name of 1 variable I get all the data from the database that is needed and display it on the site. Right now I have one problem.
I have one php file that is this:
<?php
$pName = $_POST['name'];
$db_connection = mysqli_connect('localhost','root','',"project_online_planner");
if (!$db_connection){
die('Failed to connect to MySql:'.mysql_error());
}
//insert into database
if(isset($_POST['insertComments'])){
include('connect-mysql.php');
$username = $_POST['username'];
$comment = $_POST['comment'];
$sqlinsert = "INSERT INTO user_comments (username, comment, project) VALUES ('$username', '$comment', '$pName')";
if (!mysqli_query($db_connection, $sqlinsert)){
die('error inserting new record');
}
else{
$newRecord = "1 record added";
}//end nested statement
}
//text from database
$query="SELECT * FROM user_comments where project = '$pName' ";
$results = mysqli_query($db_connection,$query);
$intro=mysqli_fetch_assoc($results);
$query2="SELECT * FROM project where name = '$pName' ";
$results2 = mysqli_query($db_connection,$query2);
$intro2=mysqli_fetch_assoc($results2);
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Project planner online</title>
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<script type="text/javascript" src="libs/ppo.js"></script>
<link rel="stylesheet" href="libs/ppo.css"/>
</head>
<body>
<div id="intro">
</div>
<div id="bgNav">
<nav id="nav">
Home
<a class="rightNav" href="register.php">Register</a>
<a class="rightNav" href="login.php">Log in</a>
</nav>
</div>
<div id="projectTile">
<span id="statusCheck"><?php print_r($intro2["status"]); ?></span>
<h2 id="prTitle"><?php print_r($intro2["name"]); ?></h2>
<div id="prPic"><img width="300" height="200" src="<?php print_r($intro2["image"]); ?>"></div>
<div id="prDescription"><?php print_r($intro2["description"]); ?></div>
</div>
<div id="comments">
<?php
while($row = mysqli_fetch_array($results))
{
echo nl2br("<div class='profile_comments'>" . $row['username'] . "</div>");
echo nl2br("<div class='comment_comments'>" . $row['comment'] . "</div>");
}
?>
</div>
<div id="uploadComments">
<form method="post" action="project.php">
<label for="name"><input type="hidden" name="insertComments" value="true"></label>
<fieldset>
<legend>comment</legend>
<label>Name:<input type="text" id="name" name="username" value=""></label><br/>
<label>Comments: <textarea name="comment" id="comment"></textarea></label>
<input type="submit" value="Submit" id="submitComment">
</fieldset>
</form>
</div>
</body>
</html>
depending on the variable $pName the content of the site changes, because it gets its content from a database and $pName stands for "project name".
$pName is determenent by the name of the picture you click on the index page which is this:
<?php
$db_connection = mysqli_connect('localhost','root','',"project_online_planner");
if (!$db_connection){
die('Failed to connect to MySql:'.mysql_error());
}
$query="SELECT * FROM project limit 5 ";
$results = mysqli_query($db_connection,$query);
$intro=mysqli_fetch_assoc($results);
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Project planner online</title>
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<script type="text/javascript" src="libs/ppo.js"></script>
<link rel="stylesheet" href="libs/ppo.css"/>
</head>
<body>
<div id="bgNav">
<div id="login">
Register
Log in
</div>
<nav id="nav">
Home
</nav>
</div>
<h2 class="titlePage">Home</h2>
<div id="bgTile">
<?php
while($row = mysqli_fetch_array($results))
{
$project = $row["name"];
echo nl2br("<img id=\"$project\" width='100px' alt='Procject name' height='100px' class='tile' src=". $row['image'] ."/>");
}
?>
<div class="tile" id="tileM"><h2>Meer</h2></div>
</div>
<form action="project.php" method="post" id="formF">
<label><input id="inputF" type="hidden" name="name"></label><br>
<input type="submit">
</form>
</body>
</html>
by clicking the image I put the name of it in a form and submit it to project.php. in project. php it is stored in the variable $pName . The problem is that once I refresh the page the $pName becomes Null and you see none of the database's data on the page. my question is: how can change this code in a way that $pName doesn't become Null when I refresh the page? and are there any suggestions on how to improve this code?
this is my javascript:
var check = null;
var form = $('#myForm');
$(document).ready(function(){
$('img').click(function(){
$('#inputF').val(this.id);
$("input[type=submit]").trigger("click");
});
});
Add Sessions to you code (as requested by #aleation).
Also, using parameters directly to query your database is very dangerous (as #jeroen mentioned).
Read up on the topic of SQL Injections and try to evaluate $pName before using it in a query.
<?php
session_start();
if(!is_null($_POST['name']))
{
$pName = $_POST['name'];
$_SESSION['pName'] = $pName;
}
elseif (array_key_exists('pName',$_SESSION)) {
$pName = $_SESSION['pName'];
}
else {
$pName = ''; // Maybe set a default here?
}
$pName = $_POST['name'];
$db_connection = mysqli_connect('localhost','root','',"project_online_planner");
if (!$db_connection){
die('Failed to connect to MySql:'.mysql_error());
}
...
Tiny glimpse into the Problem SQL Injections bring: In your example, imagine someone send's a POST request where name is ';Delete FROM project where id <>.
This would result in you loosing all your entries in the project table.
And that Query injection wouldn't even be that hard to guess.
With analyzing your website, someone could get hold of userdata, manipulate userdata, insert userdata ... you see? It is a mess.
Why are you using a $_POST variable for selecting the right content? If you make your images hyperlinks with the project name in the address, you can refresh the page without losing the variable content.
change:
echo nl2br("<img id=\"$project\" width='100px' alt='Procject name' height='100px' class='tile' src=". $row['image'] ."/>");
into
echo nl2br("<img id=\"$project\" width='100px' alt='Project name' height='100px' class='tile' src=".$row['image']."/>");
and then get $pname = $_GET['name'] instead of $pname = $_POST['name']

Categories