Store different value in the database from the forms created dynamically using PHP? - javascript

Have a look at the screenshot below.
As per the screenshot, I have the data fetched into the different blocks based on the database. For example, based on the username and password, these values are fetched from the database and displayed in different blocks. I have the PHP to store the value into the database, but the problem that I am facing is that when i try to upload it from other block, it still saves the value from the first block.
Codes as as below:
<?php
include('includes/config.php');
$upload = 'uploads/';
session_start();
$_SESSION['$userid'];
$sql = "SELECT * FROM tbl_store INNER JOIN tbl_job ON tbl_store.store_code = tbl_job.store_code WHERE username = '$userid'";
$result = mysqli_query($conn,$sql);
$rowcount=mysqli_num_rows($result);
// echo "$rowcount";
$stores = array();
$stores_add = array();
$stores_chain = array();
$job = array();
$client = array();
$brand = array();
$week= array();
$x = 1;
$imgCnt =1;
while($row = mysqli_fetch_array($result)){
echo "工作".'<br/>';
echo $row['jobs'].'<br/>'.'<br/>';
$job[] = $row['jobs'];
echo "客戶".'<br/>';
echo $row['Client'].'<br/>'.'<br/>';
$client[] = $row['Client'];
echo "牌子".'<br/>';
echo $row['Brand'].'<br/>'.'<br/>';
$brand[] = $row['jobs'];
echo "週數".'<br/>';
echo $row['week'].'<br/>'.'<br/>';
$week[] = $row['week'];
$target = $upload.'/'.$row['Client'].'/'.$row['Brand'].'/'.$row['jobs'].'/'.$row['store_code'].'/';
$testpath = $row['Client'].'/'.$row['Brand'].'/'.$row['jobs'].'/'.$row['store_code'].'/';
$_SESSION['target1'.$x] = $target;
if(!file_exists($target))
{
mkdir($target,0777,true);
}
?>
<form id='uploadForm-<?php echo $imgCnt; ?>' action = '' enctype='multipart/form-data' method = 'POST' class="form<?php echo $imgCnt; ?>">
<input type="file" class="image<?php echo $imgCnt; ?>" name="img" onChange="readURL(this);" />
<img id="blah" src="#" alt="your image" /><br/><br/>
<input type='button' id = '<?php echo $imgCnt; ?>' class='uploadPicture<?php echo $imgCnt; ?> btn btn-primary' value = '上載'>
<!-- <input type="button" value="上載" class="uploadPicture" id="upload_btn<?php echo $imgCnt; ?>"/> -->
</form>
<form enctype="application/x-www-form-urlencoded">
<table width="200" border="1">
<tr>
<td>Product</td>
<td>Promotional Price</td>
<td>Regular Price</td>
<td>Stacking</td>
</tr>
<tr>
<td><input type="text" id="product"></td>
<td><input type="text" id="pp1"></td>
<td><input type="text" id="rp1"></td>
<td><input type="text" id="stacking"></td>
</tr>
</table>
<div id ="div1">
<input type="button" value="Submit" onClick="PostData();"/><br/>
</div>
</form>
<script> src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
function PostData() {
// 1. Create XHR instance - Start
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
else {
throw new Error("Ajax is not supported by this browser");
}
// 1. Create XHR instance - End
// 2. Define what to do when XHR feed you the response from the server - Start
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status == 200 && xhr.status < 300) {
document.getElementById('div1').innerHTML = xhr.responseText;
}
}
}
// 2. Define what to do when XHR feed you the response from the server - Start
var product = document.getElementById("product").value;
var pp1 = document.getElementById("pp1").value;
var rp1 = document.getElementById("rp1").value;
var stacking = document.getElementById("stacking").value;
// var image = document.getElementById("image").value;
// 3. Specify your action, location and Send to the server - Start
xhr.open('POST', 'report.php');
//xhr.open('POST', 'config.php');
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("product=" + product + "&pp1=" + pp1 + "&rp1=" + rp1 + "&stacking=" + stacking);
//xhr.send("&pid=" + pid);
// 3. Specify your action, location and Send to the server - End
}
</script>
<?php
echo "-------------------------------------------------------".'<br/>';
$x = $x+1;
$imgCnt++;
}
?>
I have removed the code for image upload from it as it works completely fine. The problem is the data from the other block is not stored to the database. only the value for the first block is stored second time even. How to solve this problem.
PHP to store data:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "testing";
$conn = new mysqli($servername, $username, $password,
$dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO tbl_report (product,pp1, rp1,stacking)
VALUES ('$product', '$pp1', '$rp1','$stacking')";
if ($conn->query($sql) === TRUE) {
echo "Successful";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>

To expand on what #Logan Wayne pointed out...
An ID should be unique within a page. However, if more than one element with the specified ID exists, the getElementById() method returns the first element in the source code.
So, in your JavaScript, when you grab references to your table data elements, you'll always get the FIRST instance of a Document object with whatever id you provide.
// 2. Define what to do when XHR feed you the response from the server - Start
var product = document.getElementById("product").value; <-- will always return the same element
var pp1 = document.getElementById("pp1").value; <-- will always return the same element
var rp1 = document.getElementById("rp1").value; <-- will always return the same element
var stacking = document.getElementById("stacking").value; <-- will always return the same element
You'll either have to assign unique ids to your td objects, or, again as #Logan Wayne mentioned, utilize the class property of HTML DOM objects.
Classes can be used to group like elements. After assigning class names to the different columns in your table (Product, Promotional Price, Regular Price, Stacking) you can use getElementsByClassName() to get an array of the td elements.
...
var products = document.getElementsByClassName("product"); <-- array of product td elements
...

Related

Loading dynamic PHP echo in webpage without reloading the page

I have the PHP code where I get echo as my postgres database table fields I want to display these fields in my html and JavaScript based web application.for now I can load them in my webpage but I have to reload the webpage to get newly updated values. I want to get them automatically in a textbox without reloading application.i read that an ajax request would be helpful
given is the php code i am using with html to show case records but i have to reload page every time to get it updated
<?php
$host = "host = localhost";
$port = "port = 5432";
$dbname = "dbname = geoserver";
$credentials = "user = postgres password=password";
$db = pg_connect( "$host $port $dbname $credentials" );
$sql =<<<EOF
SELECT * from audit.logged_actions
ORDER BY action_tstamp_tx DESC
LIMIT 5;
EOF;
$ret = pg_query($db, $sql);
if(!$ret) {
echo pg_last_error($db);
exit;
}
while($row = pg_fetch_row($ret)) {
// echo "e = ". $row[1] . "\n";
echo "<input type='text' value='$row[14] '/>";
echo "<input type='text' value='$row[13] '/>";
}
echo "Operation done successfully\n";
pg_close($db);
?>
The problem is that after your browser renders the output of your php script, it is not connected to your php anymore. This is how HTTP works.
To be able to show the output without refreshing the whole page, you need to use javascript to make another HTTP request to your PHP script.
Something like this:
<?php
$host = "host = localhost";
$port = "port = 5432";
$dbname = "dbname = geoserver";
$credentials = "user = postgres password=password";
$db = pg_connect( "$host $port $dbname $credentials" );
$sql =<<<EOF
SELECT * from audit.logged_actions
ORDER BY action_tstamp_tx DESC
LIMIT 5;
EOF;
$ret = pg_query($db, $sql);
if(!$ret) {
echo pg_last_error($db);
exit;
}
?>
<div id='content'>
<?php while($row = pg_fetch_row($ret)) { ?>
<input type='text' value='<?= $row[14] ?>'/>
<input type='text' value='<?= $row[13] ?>'/>
<?php } ?>
Operation done successfully
<script>
(function() {
const secondsToRefresh = 5;
const Http = new XMLHttpRequest();
const url='#YOUR_PHP_SCRIPT_URL#';
setTimeout(function() {
Http.open("GET", url);
Http.send();
}, secondsToRefresh * 1000);
Http.onreadystatechange=(e)=>{
document.getElementById('data').innerHTML = Http.responseText;
}
})()
</script>
</div>";

Repeat self-processing form

My question is over creating a self-processing form that inserts to a database and then refreshes, incrementing arrays to change relevant info in the form. (though if there is an easier or better way to do this, I'm all ears).
So site is essentially a digital equivalent to an exercise journal. The user selects a template name from a select menu, then it queries the database for that template, then returns the result to a variable. The exercise names and number of sets per exercise (which will be used to calculate maximum number of form refreshes) are passed into their own respective arrays: $exerciseName[]; and $setNum[];
This is a screenshot of the form.
My question is how to go about setting up the logic so that I can keep submitting until the last set of the last exercise, where upon the final submission, would take to a different page.
I am using mysql_ functions, which I know is frowned upon, but it is for school which uses PHP 5.2.12 and that is what my teammates know so I have no other options. I haven't tried to prevent mysql injections because I don't intend to take this version online.
Here is the code for selecting type of workout and workout template:
session_start();
$user = $_SESSION['email'];
//This script
$thisScript = htmlentities($_SERVER['PHP_SELF']);
if ($user) {
require("include/connect2db.inc.php");
require("include/htmlHead.inc");
//Default page buttons
$cardioBtn = $_POST['cardioBtn'];
$resistanceBtn = $_POST['resistBtn'];
//Cardio submit
$cardioSubmit = $_POST['cardioSubmit'];
if ((empty($cardioBtn))
&& (empty($resistanceBtn))
&& (empty($selectSubmit))
&& (empty($cardioSubmit))) {
echo <<<BODYDOC
<article id="newDayArticle">
<header>
<h2>Category</h2>
</header>
<fieldset id="ndFieldset">
<form action="$thisScript" method="POST" >
<button id="cardioButton" name="cardioBtn" value="cardioBtn" >Cardio</button>
<button id="resistanceButton" name="resistBtn" value="resistBtn" >Resistance</button>
</form>
</fieldset>
<!-- <div id="selection"></div>
<div id="template"></div> -->
</article>
BODYDOC;
} else if (isset($cardioBtn)) {
//Build cardio form
echo "<h2>Cardio</h2>";
echo <<<BODYDOC
<fieldset>
<legend>Cardio Log</legend>
<form action="$thisScript" method="POST">
<input type="number" name="distance" placeholder="Distance of Run" required />
<input type="number" name="duration" placeholder="Run Duration" required />
<button id="cardioSubmit" name="cardioSubmit">Submit</button>
<button id="back" type="button" onclick="document.location.href='newday.php';" value="Back">Back</button>
</form>
</fieldset>
BODYDOC;
} else if (isset($cardioSubmit)) {
$thisScript = htmlentities($_SERVER['PHP_SELF']);
//Cardio page
$distance = $_POST['distance'];
$duration = $_POST['duration'];
$date = date("Y-m-d");
//Submit cardio data to DB
updateCardio($distance, $duration, $user, $date);
//Show user stats in table
cardioStats($distance, $duration);
//End cardio form
} else if (isset($resistanceBtn)) {
//Workout template select
$selectSubmit = $_POST['selectSubmit'];
//page to select workout template
buildSelect();
//End resistance select
}//End else if
//Require footer
require("include/htmlFoot.inc");
mysql_close();
} else {
//Redirect users not logged in
require("include/redirect.php");
} //End redirect else
Here is the select function and functions for building the form and inserting it into the database.
function buildSelect() {
//Check if resistance button submitted
//Query for template names
$query = "SELECT templateName, templatePosition
FROM templates
WHERE userID = 0
ORDER BY templatePosition";
$result = mysql_query($query)
or
die("<b>Query Failed</b><br /> $query<br />" . mysql_error());
//Find number of rows
$numRows = mysql_num_rows($result);
//Array with spaces/capitals
$templateArray = array();
//Array with no spaces/no capitals
$noSpacesArray = array();
//Get template names and build arrays
for ($i=0; $i < $numRows; $i++) {
while($row = mysql_fetch_row($result)) {
$templateName = $row[0];
$position = $row[1];
//Build array in order by pushing to $templateArray
array_push($templateArray, $templateName);
//Build array without spaces or capitals in $noSpacesArray()
$templateName = str_replace(' ', '', $templateName);
$templateName = strtolower($templateName);
array_push($noSpacesArray, $templateName);
} //End while
}//End for
//Check array values
//print_r($templateArray);
//print_r($noSpacesArray);
//Build page
echo <<<BODYDOC
<br />
<h2>Resistance</h2>
<form action="log.php" method="POST" >
<fieldset>
<legend>Resistance Templates</legend>\n
BODYDOC;
echo "<select name='mySelect' id='mySelect'>\n";
echo "\t<option value=''>Choose One</option>\n";
//Build Template
//Build Template
for ($i=0; $i < count($templateArray); $i++) {
//value='$noSpacesArray[$i] is for no spaces, all lower case
//value='$templateArray[$i] is for First letter capital, with spaces
echo "\t<option value='$templateArray[$i]'>$templateArray[$i]</option>\n";
} //End list generation
echo "</select>\n";
echo <<<BODYDOC
<input type="submit" name="selectSubmit" value="Submit" />
<br />
</fieldset>
</form>
BODYDOC;
} //End function buildSelect
//Function uses template name as argument in an SQL query to find exercise template
//Returns exercise IDs, exercise names, and # of sets per exercise in that template
function getResult($template) {
//Query template name and get templateID
$query = "SELECT templateID
FROM templates
WHERE templateName = '$template'";
$result = mysql_query($query)
or
die("<b>Query Failed</b><br />$query<br />" . mysql_error());
//This part made me smash my head into a wall
$templateID = mysql_fetch_object($result);
$templateID = $templateID->templateID;
//Get exercise template, exercise names, and number of sets with query
$query = "SELECT exerciseID, exerciseName, numSets
FROM exercises
WHERE templateID = $templateID";
$result = mysql_query($query)
or
die("<b>Query Failed</b><br />$query<br />" . mysql_error());
return $result;
} //End getExercises
//Get number of exercises
function getExerciseNum($result) {
//Get number
$numRows = mysql_num_rows($result);
return $numRows;
}//End getExerciseNum
//Get exercise names as array
function exerciseList($result, $numRows) {
//Initialize exercise name array
$exerciseArray = array();
//Exercise array increment
//
for ($i=0; $i < $numRows; $i++) {
while($row = mysql_fetch_row($result)) {
$exerciseName = $row[1];
//Push names to array
array_push($exerciseArray, $exerciseName);
} //End while
} //End for
//Return name array
return $exerciseArray;
}//End exerciseList()
//Get number of sets per exercise
function getSets($result, $numRows) {
//
$setsArray = array();
//
for ($i=0; $i < $numRows; $i++) {
while($row = mysql_fetch_row($result)) {
$numSets = $row[2];
//Push to array
array_push($setsArray, $numSets);
} //End while
} //End for
//Return array
return $setsArray;
} //End setsPerExercise()
//Build log form using query result and exercise name increment ($x)
function buildLog($thisScript, $template, $exerciseArray, $setsArray, $numRows, $date) {
$logSubmit = $_POST['logSubmit'];
//echo "numRows = " . $numRows;
static $x = 0;
echo "<br />X = $x";
if (empty($logSubmit)) {
echo "<form action='$thisScript' method='POST' name='log' id='log'>\n";
echo "<fieldset>\n";
echo "<legend>$template</legend>\n";
echo "<h2>$exerciseArray[0]</h2>\n";
echo "<input type='hidden' name='exerciseArray[]' value='$exerciseArray[$x]'/>\n";
$j = 1;
//Generate exercise form with loop
for ($i=0; $i < $setsArray[$i]; $i++) {
echo "<fieldset>";
echo "<legend>Set $j</legend>\n";
//Use $template in a hidden value to work around issue of value being lost after submitting form
echo <<<BODYDOC
<label>Weight</label>
<input type="text" name="weight[]" required /> \n
<label>Reps</label>
<input type="number" name="reps[]" required /> \n
<label>Rest Time</label>
<input type="number" name="rest[]" required /> \n
<label>Notes</label>
<textarea name="notes[]"></textarea>
<input type="hidden" name="set[]" value='$j' />
<input type="hidden" name='mySelect' value='$template' />
</fieldset>
BODYDOC;
$j++;
} //End form for loop
echo "<br /><button type='submit' name='logSubmit'>Submit</button>\n";
echo "</fieldset>\n";
echo "</form>\n";
echo "<p><a href='newday.php'>Back</a></p>\n";
//Increment exerciseNameArray counter so next form dispays next exercise name
} //End if empty submit
if (isset($logSubmit)) {
//POSTed
$template = $_POST['mySelect'];
$set = $_POST['set'];
$weight = $_POST['weight'];
$reps = $_POST['reps'];
$rest = $_POST['rest'];
$notes = $_POST['notes'];
//Update Log
updateLog($user, $template, $exerciseArray, $set, $weight, $reps, $rest, $notes, $date);
} //End else if
} //End buildLog($template, $x) function
function updateLog($user, $template, $exerciseArray, $set, $weight, $reps, $rest, $notes, $date) {
//Insert data with query
$numRows = count($exerciseArray);
echo "count exerciseArray = " . $numRows;
for ($i=0; $i < $numRows; $i++) {
$insert[$i] = "INSERT INTO stats_resistance
(userID, template, exerciseName, set, weight, reps, rest, notes, date)
VALUES
('$user','$template', $exerciseArray[$i]','$set[$i]','$weight[$i]','$reps[$i]','$rest[$i]', '$notes[$i]', '$date')"
or
die(mysql_error());
$result[$i] = mysql_query($insert[$i])
or
die(mysql_error());
} //End for
//Increment $x and pass it back to buildLog
//$x++;
//return $x;
} //End updateLog()
Here is the log.php form file:
Edit: Added htmlentities to PHP_SELF and changed some logic.
session_start();
//User
$user = $_SESSION['email'];
$date = date("Y-m-d");
//
$template = $_POST['mySelect'];
//Set log submit button
$logSubmit = $_POST['logSubmit'];
//Check if user is signed in
if ($user) {
if ($template) {
require_once("include/connect2db.inc.php");
require_once("include/htmlHead.inc");
//Get this script
$thisScript = htmlentities($_SERVER['PHP_SELF']);
//Return query
$result = getResult($template); //Returns result of template
//numRows
$numRows = getExerciseNum($result);
//Return exercise array
$exerciseArray = exerciseList($result, $numRows); //Returns set of exercises in template
//For some reason, $result and $numRows is empty after being passed into $exerciseArray
//Reinitialize
$result = getResult($template); //Returns result of template
//numRows
$numRows = getExerciseNum($result);
//Return sets per exercise as array
$setsArray = getSets($result, $numRows);
//Build form
buildLog($thisScript, $template, $exerciseArray, $setsArray, $numRows, $date);
//Require Footer
require_once("include/htmlFoot.inc");
mysql_close();
} else if (empty($template)){
//Do something if template is empty
require_once("include/connect2db.inc.php");
require_once("include/htmlHead.inc");
echo "<p>Seems the template is empty</p>\n";
echo "<p>Template = $template</p>\n";
//Require Footer
require_once("include/htmlFoot.inc");
mysql_close();
} //End if ($template)
} /*else if (($user) && (isset($logSubmit))) {
//If user is signed in and log has been submitted
//Get form values and insert into database
require("include/connect2db.inc.php");
require_once("include/htmlHead.inc");
//Get this script
$thisScript = htmlentities($_SERVER['PHP_SELF']);
echo "<pre>\n";
echo "print_r of POST<br />";
print_r($_POST);
echo "</pre>\n";
//Get Workout and POST info
$template = $_POST['mySelect'];
$set = $_POST['set'];
$weight = $_POST['weight'];
$reps = $_POST['reps'];
$rest = $_POST['rest'];
$notes = $_POST['notes'];
//Check if form is submitted, if so, insert into db
updateLog($user, $template, $exerciseArray, $set, $weight, $reps, $rest, $notes, $date);
echo "<p>Entered update log else/if block</p>\n";
//Require Footer
require_once("include/htmlFoot.inc");
mysql_close();
}*/ else if (!isset($user)) {
//If user not logged in
require("redirect.php");
}
You can use PHP_SELF (eg <?php echo htmlentities ($ _ SERVER ['PHP_SELF']); ?>) In the action of the form. See this article which explains why we need htmlentities. This PHP_SELF variable contains the path to the current script.
All the logic you can place where you have, before the template, where you should check the following:
Did happen a page submit?
If yes, check for errors with submitted data.
If there are no errors treats and saves the information. If there are send an array with errors for the template.
If not, nothing to do.
Thus, when there is submission of the form everything will always be submitted on the same page.

PHP Mysql Table Pagination

Ive been try to make a page with Pagination on table. Upon button click, the table in main.php got populated by the first 16 rows retrieved from the query in page.php. For example the retrieved rows were 20. So there would be an excess of 4 for the second page. The thing is when I clicked the "Next" button to show the missing 4 records, the page is then diverted to page.php with the missing records. What I want to happen is for the 20 records in main.php be replaced by the 4 records.
MAIN.PHP
<div id="section">
<head3>Asset Assignment</head3><br><br>
<table>
<td>
<tr>Search Asset:</tr>
<tr><input type="text" id="sidt" name="sid"></tr>
<tr><input type="button" name="searchSub" value="Search" onClick="searchItem()"></tr>
</td>
</table><br>
<table>
<tr>
<td>Employee ID</td>
<td>Asset Serial Number</td>
</tr>
<tr>
<td><input type="text" name="empID"></td>
<td><input type="text" name="srlID"></td>
</tr>
<tr>
<td align="right"><input type="button" name="assign" value="Assign" onClick="assignItem()"></td>
</tr>
</table><br>
</div>
<div id="section2"></div>
JAVASCRIPT
function searchItem()
{
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var data = "asid=" + document.getElementById("sidt").value;
xhr.open("POST", "page.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(data);
xhr.onreadystatechange = display_data;
function display_data()
{
if (xhr.readyState == 4)
{
if (xhr.status == 200)
{
document.getElementById("section2").innerHTML = xhr.responseText;
}
else
{
alert('There was a problem with the request.');
}
}
}
}
function assignItem(){}
PAGE.PHP
<?PHP
session_start();
$dbHost = "localhost";
$dbUser = "root";
$dbPass = "password";
$dbDatabase = "awsims";
$db = new PDO("mysql:dbname=$dbDatabase;host=$dbHost;port=3306", $dbUser, $dbPass);
if (!isset($_GET['startrow']) or !is_numeric($_GET['startrow'])) {
$startrow = 0;
} else {
$startrow = (int)$_GET['startrow'];
}
$sql = $db->prepare("SELECT * FROM assets LIMIT $startrow, 16");
$sql->execute();
$fetch = $sql->rowCount();
$num=$fetch;
if($num>0)
{
echo "<table style='width: 100%' border='1'>";
echo "<tr><td>ID</td><td>Drug</td><td>quantity</td></tr>";
for($i=0;$i<$num;$i++)
{
$row = $sql->fetch(PDO::FETCH_ASSOC);
$a = $row['SerialNumber'];
$b = $row['AssetType'];
$c = $row['AssetSubType'];
echo "<tr>";
echo "<td>$a</td>";
echo "<td>$b</td>";
echo "<td>$c</td>";
echo "</tr>";
}
echo "</table>";
}
echo '<a href='.$_SERVER['PHP_SELF'].'?startrow='.($startrow+16).'>Next</a>';
$prev = $startrow - 16;
//if ($prev >= 0)
echo '<a href='.$_SERVER['PHP_SELF'].'?startrow='.$prev.'>Previous</a>';
?>
Try changing your sql statement to as following query.
$sql = $db->prepare("SELECT * FROM assets LIMIT 16 OFFSET $startrow");
The next and previous link code should be like following.
echo '<a href='.$_SERVER['PHP_SELF'].'?startrow='.($startrow+1).'>Next</a>';
$prev = $startrow - 1;
echo '<a href='.$_SERVER['PHP_SELF'].'?startrow='.$prev.'>Previous</a>';
Here is the easiest and smartest PHP MySQL Pagination example I had ever read! Very well explained and a full code is provided which is tested and working 100%.

How to add an option to a html select, from input received from the user

I have a select with client names that is populated from a SQL database, that part works fine, but occasionally it is necessary to add a new client. So I want a button that displays a popup where the user can provide the new client name and have it added to the select as a new option. Below is the relevant code that I have tried. The problem is that when either button is pressed on the prompt it causes the form to submit and reloads the page. Thanks in advance.
<form action = "AddNewJob.php" method = "post">
...
<td><?php echo $dropdown3 ?><button onclick="myFunction()">Add new client</button>
<script>
function myFunction() {
var client = prompt("Please enter client name", "New client");
if ((client != null) && (!client.equals("New client"))) {
var select = document.getElementById("Client");
select.options[select.options.length] = new Option(client, client);
document.getElementById('newclientfield').value = client;
}
}
</script></td>
...
<p><input type="hidden" id="newclientfield" value="" /></p>
<p align="center"><input type="submit" value="Submit" name="btnAdd"></p>
</form>
$dropdown3 is the select that is created in PHP from the SQL database
EDIT:
Here is the code for $dropdown3:
$Clients = array();
$result = mysqli_query($link, "SELECT Name FROM tblClients");
$i = 0;
$rownum = mysqli_num_rows($result);
while ($i < $rownum){
mysqli_data_seek($result, $i);
$row = mysqli_fetch_row($result);
$Clients[] = $row[0];
$i++;
}
$dropdown3 = "<select size=\"1\" name=\"Client\" id=\"Client\">";
$i = 0;
while($i < count($Clients)){
$dropdown3 .= "\r\n<option value = '" . $Clients[$i] . "'>" . $Clients[$i] . "</option>";
$i++;
}
$dropdown3 .= "\r\n</select>";
That part works fine.
This is the final working code for the button that requests user input and then adds the option to the select (as well as a hidden field for POST purposes so it can be added to the database).
<button type="button" onclick="myFunction()">Add new client</button>
<script>
function myFunction() {
var client = prompt("Please enter client name", "New client");
if ((client != null) && (client != "New client")) {
var select = document.getElementById("Client");
select.options[select.options.length] = new Option(client, client);
document.getElementById('newclientfield').value = client;
select.selectedIndex=select.options.length - 1;
}
}
</script>

How to retain the values displayed in the HTML after it is fetch from the PHP?

I have an HTML page that takes the user input and displays the output based on the database. I have a hyperlink to the other pages. I want when I navigate from first page to other HTML page, I add a back button and it shoud return to the first page but it should show the fetched values. Here is the code below.
1st HTML:
<script>
function PostData() {
var online = navigator.onLine;
if(online){
// 1. Create XHR instance - Start
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
else {
throw new Error("Ajax is not supported by this browser");
}
// 1. Create XHR instance - End
// 2. Define what to do when XHR feed you the response from the server - Start
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status == 200 && xhr.status < 300) {
document.getElementById('div1').innerHTML = xhr.responseText;
}
}
}
// 2. Define what to do when XHR feed you the response from the server - Start
var userid = document.getElementById("userid").value;
var pid = document.getElementById("pid").value;
// var image = document.getElementById("image").value;
// 3. Specify your action, location and Send to the server - Start
xhr.open('POST', 'login3.php');
//xhr.open('POST', 'config.php');
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("userid=" + userid + "&pid=" + pid);
//xhr.send("&pid=" + pid);
// 3. Specify your action, location and Send to the server - End
}
else{
alert("You are offline");
}
}
</script>
</head>
<body>
<form>
<label for="userid">User ID :</label><br/>
<input type="text" name ="userid" id="userid" /><br/>
<label for="pid">Password :</label><br/>
<input type="password" name="password" id="pid" /><br><br/>
<div id="div1">
<input type="button" value ="Login" onClick="PostData()" />
</div>
</form>
</body>
PHP:
<?php
if(isset($_POST['userid'],$_POST['pid']))
{
$userid = trim($_POST["userid"]);
$pid = trim($_POST["pid"]);
$sql = "SELECT * FROM demo WHERE username = '$userid' and password = '$pid'";
$result = mysqli_query($conn,$sql);
$row = mysqli_fetch_array($result);
echo $row['week'].'<br/>'.'<br/>';
echo '<a href="2ndHTML.html"/>'.$row['day1'].'</a>'.'<br/>';
?>
2nd HTML:
<body>
<form enctype="multipart/form-data" id="form" action="" method="post">
<input type="file" id="imageid" name="image" onchange="readURL();" />
<img id="blah" src="#" alt="your image" /><br/><br/>
<input type="button" value="upload" onclick="javascript:uploadInage();" />
BACK
</form>
</body>
I want to retain the values fetched on the 1stHTML.html
It's best to use session. Once the user has completed the first form set a session to signal that, so when they return to the first page it will read the session and automatically redirect them to the necessary page.
You'll need to put this at the top of your 1sthtml.php and 2ndhtml.php page to signal that you want to use sessions:
<?php
session_start();
On your 1sthtml.php page you'll need to set the session information:
<?php
if(isset($_POST['userid'],$_POST['pid']))
{
$userid = trim($_POST["userid"]);
$pid = trim($_POST["pid"]);
$sql = "SELECT * FROM demo WHERE username = '$userid' and password = '$pid'";
$result = mysqli_query($conn,$sql);
$row = mysqli_fetch_array($result);
echo $row['week'].'<br/>'.'<br/>';
echo '<a href="2ndHTML.html"/>'.$row['day1'].'</a>'.'<br/>';
// ---- SET SESSION HERE ---
$_SESSION['stage'] = 1;
}
?>
And then, on the 1sthtml.php again you'll need to check to see if that session variable exists, if it does then forward onto the page you want. So, at the top of your 1sthtml.php, next to your previous session_start():
<?php
session_start();
if (isset($_SESSION['stage'])) {
header('Location: 2ndhtml.php');
exit();
}

Categories

Resources