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

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>

Related

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.

Form not running PHP

So I'm working on an assignment for my class in which I am supposed to take a username and password and check it against a list contained in a table on a database I am connecting too.
Problem is when I am clicking the submit button nothing is happening I think this is likely to be some sort of error in syntax. Since I am new to PHP there is a good possibility it is something obvious, but not so much to me.
I have my database data stored in two PHP arrays (one for each field). I then converted the arrays to json which I will use in my JavaScript function that will be checked against the user inputted data.
I am including a form, a PHP script, and a JavaScript script in one document could this cause the issue?
Here is my code and thank you for any help!
<html>
<body>
<?php
/*config is included in order to protect my login info*/
require('config.php');
Echo "Project 4";
/*SQL connection*/
$conn = new mysqli(DB_HOST,DB_USER,DB_PASS,DB_NAME);
/*Checking Connection*/
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$sql = "SELECT * FROM p4Data";
$data2 = mysqli_query($conn, $sql);
/*Display Data*/
echo "<table border = 1 style='float:left'>
<tr>
<th>Username</th>
<th>Password</th>
</tr>";
//Array Declarations
$usernameArr = [];
$passwordArr = [];
while($records = mysqli_fetch_array($data2)){
array_push($usernameArr,$records["username"]);
array_push($passwordArr,$records["password"]);
}
echo "</table>";
//JSON Conversion
$usernameJson = json_encode($usernameArr);
$passwordJson = json_encode($passwordArr);
mysqli_close($conn);
?>
<!-- JAVA SECTION -->
<script type="text/javascript">
var obj = JSON.parse('<?= $usernameJson; ?>');
var obj2 = JSON.parse('<?= $passwordJson; ?>');
function verifUser(){
var usernameData = document.getElementById("username").value;
var passwordData = document.getElementById("password").value;
for (i = 0; i < 30; i++){
if(usernameData == obj[i]){
alert("Username verfied at " + i);
indexLocated = i;
break;
}
}
}
</script>
<form name='form-main'>
Username: <input type="text" id="username"><br>
Password: <input type="password" id="password"><br>
<input type="button" value="Login >>" id="submitButton"
onclick="verifUser()">
</form>
</body>
</html>
You can use post method to get the value of user input like this
<form method="post">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" name="submit" value="login">
</form>
and use this php code to get value when form is submitted
if(isset($_POST['submit'])){
$username_input = $_POST['username'];
$password_input = $_POST['password'];
}
Then make a query to sql where username = $username and password = $password. Like below
$sql query = " SELECT * FROM TABLE WHERE username = $username and password = $password";
And use
$num_rows = mysqli_num_rows($sql_query);
Now do a check of $num_rows = 1 that means input username and password is valid else echo Not valid
if($num_rows = 1){
**some code **
}else{
echo "Invalid information provided";
};

How can I make the delete buttons fully functional with right ID using php, AJAX or MySQL?

I am having a little problem with this, every delete button is supposed to delete the record of its own id. If we click 164 it must delete the record of 164. It works fine if I remove the ajax and ask the form to validate directly, but if I use AJAX it only deletes the record of 1st record regardless of what button I press e.g. in current scenario it will always delete the record of 159 even if I press 164 button. My code gives the following output: Remember it works fine if I ask the form to validate directly from other PHP file.
This is my output please have a look at it. Its quite simple!
if(is_numeric($lumens) && $lumens < 5000 && $lumens >250){
if(is_numeric($THD) && $THD <= 20 && $THD >=0){
if(is_numeric($scaled_power_factor) && $scaled_power_factor >=0.9){
if(is_numeric($scaled_cct) && $scaled_cct <=5700){
if(is_numeric($scaled_cri) && $scaled_cri >=65){
if(is_numeric($scaled_input_power)){
$con = new mysqli(localhost, asd, myp, rec);
if(!$con){
echo "Couldn't connect to the database";
}
else{
$id = $_SESSION['user_id'];
$query = "INSERT INTO scaling_performance_data SET
MODEL_NUMBER = '$model_number',
LUMENS = '$lumens',
scaled_luminaire_efficacy = '$lm_w',
scaled_input_power = '$scaled_input_power',
THD = '$THD',
SCALED_POWER_FACTOR = '$scaled_power_factor',
SCALED_CCT = '$scaled_cct',
SCALED_CRI = '$scaled_cri',
HOUSING_VARIATION = '$housing_variation',
user_id = '$id'
";
if($con->query($query)){
$sql = "SELECT * FROM scaling_performance_data WHERE user_id='$id';";
$result = $con->query($sql);
if($result){
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
?>
<form>
<table>
<tr>
<th>adsf</th><th>adsf</th><th>adsf</th><th>adsf</th><th>adsf</th><th>adsf</th><th><input type="button" name ="delete_id" id="delete_id" value="<?php echo $row['ID'];?>" onclick="vlid();"/></th>
</tr>
</table>
<script type="text/javascript">
function vlid(){
var delete_id = $('#delete_id').val();
alert(delete_id);
$.post('validator.php',{
postdelete_id : delete_id
},
function(data){
$('#del').html(data);
}
)
}
</script>
</form>
<?php
}
}
validator.php is:
$id = $_POST['postdelete_id'];
$con = new mysqli(localhost, asd, myp, rec);
if(!$con){
echo "Couldn't connect to the database";
}
else{
$query="DELETE FROM scaling_performance_data WHERE ID='$id';";
if($con->query($query)){
echo "Your Result was deleted successful";
echo $id;
}else{
echo "There was a problem Please try again later";
}
}
The problem is that in your vlid() function, JQuery is only selecting the first element with id = delete_id. I would try passing the ID to the vlid() function like this:
<input type="button" ... onclick="vlid(<?php echo $row['ID'];?>)"/>
And then modify your vlid() function to accept the ID parameter.
Try var delete_id = $(event.target).val(); instead of: var delete_id = $('#delete_id').val();
1st ID must be unique so use
class="delete_id"
instead of
id="delete_id"
2nd remove onclick="vlid();" and use
$(document).ready(function(){
$('body').on('click','.delete_id',function(){
var getValue = parseInt($(this).val());
$.post('validator.php',{postdelete_id : getValue},function(data){
$('#del').html(data);
});
});
});
and to remove the tr which deleted use
$(document).ready(function(){
$('body').on('click','.delete_id',function(){
var thisBtn = $(this);
var getValue = parseInt(thisBtn .val());
$.post('validator.php',{postdelete_id : getValue},function(data){
$('#del').html(data);
thisBtn.closest('tr').remove();
});
});
});

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

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

How to get multiple value from mysql populated dropdown and create table using those values

I have searched a lot on the internet for a possible solution to my issue, but there is nothing that can help me. I am not an expert on PHP/MySQL.
My Issue:
I have two dropdown select box. On the basis of first dropdown option, second dropdown options will be populated. This is working.
Now I need to get all the values of the second dropdown by selecting one option (like "Select All"), or by clicking on a button and post (which I have used as I don't know how to use the Select All option).
Upon POST, it should create separate tables for each value. And the table name would be something like "table_valuename".
And also what will be the query to select data from a different table using those values and store them to their respective databases. Databases which are getting created on the above step.
Here is my code:
<?php
$db = new mysqli('localhost','root','redhat','echodeve_mfb_temp');//set your database handler
$query = "SELECT bp_id,bp_name FROM mfb_billing";
$result = $db->query($query);
while($row = $result->fetch_assoc()){
$categories[] = array("bp_id" => $row['bp_id'], "val" => $row['bp_name']);
}
$query = "SELECT bp_id, hospital_name FROM mfb_hospital";
$result = $db->query($query);
while($row = $result->fetch_assoc()){
$subcats[$row['bp_id']][] = array("bp_id" => $row['bp_id'], "val" => $row['hospital_name']);
}
$jsonCats = json_encode($categories);
$jsonSubCats = json_encode($subcats);
?>
<html>
<head>
<script type='text/javascript'>
<?php
echo "var categories = $jsonCats; \n";
echo "var subcats = $jsonSubCats; \n";
?>
function loadCategories(){
var select = document.getElementById("categoriesSelect");
select.onchange = updateSubCats;
for(var i = 1; i < categories.length; i++){
select.options[i] = new Option(categories[i].val,categories[i].bp_id);
}
}
function updateSubCats(){
var catSelect = this;
var catid = this.value;
var subcatSelect = document.getElementById("subcatsSelect");
// subcatSelect.options.length = 0; //delete all options if any present
for(var i = 1; i < subcats[catid].length; i++){
subcatSelect.options[i] = new Option(subcats[catid][i].val,subcats[catid][i].hospit);
}
}
function selectAll()
{
selectBox = document.getElementById("subcatsSelect");
for (var i = 0; i < selectBox.options.length; i++)
{
selectBox.options[i].selected = true;
}
}
</script>
</head>
<body onload='loadCategories()'>
<form id="reportvalue" action="file2.php" method="post">
<select id='categoriesSelect'>
<option value="1">Select Billing Provider</option>
</select>
<select name="hospitalname" id="subcatsSelect" multiple="multiple">
<option value="all">Select Hospital</option>
</select>
<?php
//$a = $_REQUEST['hospitalname'];
//echo $a;
//foreach ($_GET['hospitalname'] as $selectedOption)
// echo $selectedOption."\n";
?>
<input type="submit" value="generate" onclick="selectAll();">
</form>
</body>
</html>

Categories

Resources