Hidden table row not displaying correct information - javascript

I've having some issue with the Javascript. I have a table that shows the basic information of the customer when an employee conduct a search base on the customer name. When the employee clicks on "View Sales History" the hidden table row of the particular customer's sales history will appear.
I've have no problem displaying the sales history of all the customer's returned from the search when I change the css display to "table-row". However it would only display the first customer's sales history whenever I hide the table row and include the javascript to display the hidden row.
This is what I've tried doing so far, hopefully someone can help me out here.
while($row = mysql_fetch_assoc($result)) {
$id = $row["id"];
$cfname = $row["f_name"];
$clname = $row["l_name"];
$cemail = $row["email"];
$ccompany = $row["company_name"];
$year = $row["year"];
$product = $row["product"];
$employee = $row["employee"];
$status = $row["status"];
echo '<tr>
<td>'.$cfname.' '.$clname.'</td>
<td>'.$cemail.'</td>
<td>'.$ccompany.'</td>
<td> <h4 id="vsalesHistory" onclick="vsalesHistory()">View Sales History</h4></td>
</tr>';
echo '<thead id="salesHistoryHead">
<tr>
<th>Date of Sales</th>
<th>Type of Product</th>
<th>Previous Sales Manager</th>
<th>Job Status</th>
</tr>
</thead>';
echo '<tr id="salesHistory">
<td>'.$year.'</td>
<td>'.$product.'</td>
<td>'.$employee.'</td>
<td>'.$status.'</td>
</tr>';
}
echo '</table>';
and this is my JS script
function vsalesHistory(){
var e = document.getElementById('salesHistoryHead');
var f = document.getElementById('salesHistory');
if(e.style.display == 'table-row'){
e.style.display = 'none';
}else{
e.style.display = 'table-row';
}
if(f.style.display == 'table-row'){
f.style.display = 'none';
}else{
f.style.display = 'table-row';
}
}

You are creating multiple rows with the same ID, which is not a good idea. Instead, use the row ID to create unique iDs, like:
echo '<thead id="salesHistoryHead' . $id . '">
<tr>
<th>Date of Sales</th>
<th>Type of Product</th>
<th>Previous Sales Manager</th>
<th>Job Status</th>
</tr>
</thead>';
echo '<tr id="salesHistory' . $id . '">
<td>'.$year.'</td>
<td>'.$product.'</td>
<td>'.$employee.'</td>
<td>'.$status.'</td>
</tr>';
Then pass the ID with the button action, e.g.
<td> <h4 id="vsalesHistory" onclick="vsalesHistory(' . $id . ')">View Sales History</h4></td>
If $id is a string, you would need to quote it in the call to vsalesHistory.
Now you can use the ID in your Javascript to pick the single right set of information.
For example:
function vsalesHistory(id){
var e = document.getElementById('salesHistoryHead'+id);
var f = document.getElementById('salesHistory'+id);
...

Related

Button to remove table row is not getting added to html table

I am trying to add a button to remove the table row when clicked. This should be placed next to data that is outputted from MySQL database.For some reason the button is not outputting, below is the code for my table:
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Subject</th>
<th>Message</th>
<th>Have you replied?</th>
</tr>
</thead>
<?php //makes a connection to the database
$conn = mysqli_connect("localhost", "root", "", "messages");
if ($conn->connect_error) {
die("Connection Failed:" . $conn->connect_error);
}
$sql = "SELECT * FROM tbl_messages";
$result = $conn->query($sql);
if ($result->num_rows > 0) { //fills the table with the content in the database
while ($row = $result->fetch_assoc()) {
echo '<tr><td>' . $row["name"] . '</td><td>' . $row["email"] . '</td><td>' . $row["subject"] . '</td><td>' . $row["message"] . '</td><td><button id="replied" onclick="DeleteRow()"></button>' . '</td></tr>';
}
echo "</table";
} else {
echo "0 result";
}
$conn->close();
?>
</table>
And this is the javascript code to delete the table row:
<script>
function DeleteRow() {
var td = event.target.parentNode;
var tr = td.parentNode; // the row to be removed
tr.parentNode.removeChild(tr);
}
</script>
Picture of my table row
The blank space underneath the "Have you replied" table header is where the button should be but its not there
I am still learning PHP so any replies on how I can fix this would be very helpful please

how to display a table based on a column value (CSV Path)

I have a table as such
File Name
File path
MyFile1.csv
D:\tmp\MyFile1.csv
MyFile2.csv
D:\tmp\MyFile1.csv
So Far , i'm displaying my main table as such
<div class="panel-body table-responsive">
<table class="table table-striped table-bordered" id="example">
<thead>
<tr style="background-color:#555;color:white;">
<th>File Name</th>
<th>File path</th>
</tr>
</thead>
<tbody>
<?php
$query_table = "select File_Name as File_Name, file_path as file_path from table_logs ";
$result_table = pg_query($dbconn1, $query_table) or die('Échec de la requête : ' . pg_last_error());
while ($list_table = pg_fetch_assoc($result_table)) {
echo '<tr><td>' . $list_table['File_Name '] . '</td><td>' . $list_table['file_path '] . '</td></tr>';
}
?>
</tbody>
<tfoot>
<tr>
<th>File Name</th>
<th>File path</th>
</tr>
</tfoot>
</table>
</div>
To access the csv files a transform them dynamicaly to sub tables based on the file paths i'm using this php code and that working fine
<?php
$query_table = "select File_Name as File_Name, file_path as file_path from table_logs";
$result_table = pg_query($dbconn1, $query_table) or die('Échec de la requête : ' . pg_last_error());
while ($list_table = pg_fetch_assoc($result_table)) {
echo "<br><html><body><table >\n\n";
$f = fopen($list_table['file_path'], "r");
while (($line = fgetcsv($f)) !== false) {
echo "<tr>";
foreach ($line as $cell) {
echo "<td>" . htmlspecialchars($cell) . "</td>";
}
echo "</tr>\n";
}
fclose($f);
echo "\n</table></body></html>";
}
?>
My output is as such for the file path 1 : D:\tmp\MyFile1.csv
Key
Value
key1
value1
key2
value2
My output is as such for the file path 2 : D:\tmp\MyFile2.csv
Key
Value
key1
my row 1
key2
my row 2
My question is how display a table when clicking on the value of a File Path
Do i have to add a button the main table ?
How could i achieve the link between the main table and the sub tables ?
How to use ajax to pass the variable and display in Javascript the result ?
You can use an anchor tag for that and pass the filename with your link than grab it from the URL and show data of that file. You can get your filename when people click on your file paths.
D:\tmp\MyFile1.csv
<br>
<?php echo isset($_GET['fileanme']) && $_GET['fileanme'] ? $_GET['fileanme'] : '' ?>

Mixing php with javascript.Toggle reveal /hide fetched data

This is the update page, where the customer shopping basket content is displayed. The shopping details are kept in 'mcart' table.
It consists of mcartId,mcookieId,mpr,mqty,mpn & des fields.
The main part number,prices,description & priced discounts are taken from table2.
Typical update page will look this:
p-n price qty remove? qty discounts
s-12 10.25 1 remove Items
b-12 3.64 1 remove Items
'Items' contains discount range which is fetched from another table e.g.
Items:
1-5 ,0%
6-19 ,12%
20-39 ,25%
40-59 ,33%
60-99 ,37%
100-199 ,42%
200-499 ,45%
500-9999 ,48%
These discount rates are hidden and will be revealed once a user clicks on 'items' to toggle hide or reveal.
eg, if customer buys 1-5 item price would be say £2.50, but 6-9, will eb reduced to say £1.90 and so on.
The discount range is hidden and should ideally reveal it for any item they click on, under 'item'.
At present it only shows the discounts for the 1st item, as I would expect, no matter which item I choose.
How can I change the javascript, so it would remember which item I have clicked on and show only that item's discount percentage?
Please help!
<script type="text/javascript">
function toggle(id){
var e=document.getElementById(id);
if (e.style.display == '')
{
e.style.display = 'none';
}
else {
e.style.display = '';
}
}
</script>
<?php
// ====== Connection to database ==============================
include("order/connection.php");
// ============== identify if item has been removed or qty changed=> whats the part number? =========
$id = $_GET[id];
$mqty = $_POST[chmqty];
$mpn = $_POST[mmpn];
// ================If qty has been changed ==============
if (isset($_POST['chmqty']))
{
$stmt = $pd->prepare('SELECT * FROM table2 WHERE
part_number=:part_number' );
$stmt->execute(array(':part_number' => $mpn));
$row = $stmt->fetch(PDO::FETCH_BOTH);
// ====== Get the correct price break =====================
for($in =1 ; $in <= 8; $in++)
{
$bb=$row["price_break".($in)];
$halves =explode("-",$bb);
$firstnumber=$halves[0];
$secondnumber=$halves[1];
If ($mqty >= $firstnumber && $mqty <=
$secondnumber)
{
$price=
number_format($row[("price_each".$in)], 2, ".", ",");
}
}
// ================================
$query = "UPDATE mcart SET mqty='$mqty', mpr='$price'
WHERE mcookieId = :cookie AND mpn= :part";
$stmt3=$pd->prepare($query);
$stmt3->BindValue(':cookie',$_COOKIE[mcartId], PDO::PARAM_STR);
$stmt3->BindValue(':part',$_POST[mmpn], PDO::PARAM_STR);
$stmt3->execute();
}
// =============== If DELETE button has been pressed ======
if (!empty($id))
{
$statement2= 'DELETE FROM mcart WHERE mcookieId=? AND mpn=?';
$stmt1 = $pd->prepare($statement2);
$stmt1->execute(array($_COOKIE[mcartId],$id));
}
// ================= Display customer Shopping Basket ==========
$statement= "SELECT * FROM mcart WHERE mcookieId=:cookie";
$stmt2 = $pd->prepare($statement);
$stmt2->bindParam(':cookie', $_COOKIE[mcartId], PDO::PARAM_STR);
$stmt2->execute();
?>
<Table class="tupdate">
<tr >
<th class="pn"> p-n
</th>
<th class="pr"> price
</th>
<th class="qty"> qty
</th>
<th class="remove"> remove?
</th>
<th class="disc">discounts
</th>
</tr>
<?php
while ($row = $stmt2->fetch(PDO::FETCH_ASSOC))
{
echo "<tr class='basket1'>";
// ================ Show Part Numbers ===============
echo "<td class='basket1'>";
echo $row['mpn'];
echo "</td>";
// ================ Show Proces ===============
echo "<td class='basket1'>";
echo $row['mpr'];
echo "</td>";
echo "<form method='POST' action='".$_SERVER['PHP_SELF']."'>";
// ===== Show Qty already in shopping basket that can be changed,
// =====get qty & partnumber if update is clicked ======
echo "<td class='basket1'>";
echo "<input type='number' size='3' value='".$row['mqty']."'
name='chmqty' class='chmqty'>" ;
echo "<input type='hidden' name='mmpn' value='".$row['mpn']."'>";
echo" <Input type='submit' value='update'>";
echo "</form>";
echo "</td>";
// == An item can be removed from basket, get the part number ===
echo "<td class='basket1'>";
echo "<a href='update1.php?id="
.$row['mpn'].
"'>remove</a>";
echo "</td>";
// ===== Show the price break range and associated discount
percentage from Table2 ====
echo "<td class='basket1'>";
?>
Items
<span id="objDetails" style="display:none">
<?php
// ====== calculate how many times in basket and the total
price so far =====
$totq=$row["mqty"];
$totqty=$totqty+$totq;
$totp=$row["mqty"]*$row["mpr"];
$totpr=$totpr+$totp;
// ====== Connect to Table 2, Find the relevant p-n and its
discount percentage and lis it =========
$stmt = $pd->prepare("SELECT * FROM table2 LEFT JOIN mcart ON
table2.part_number = mcart.mpn WHERE table2.part_number
=:part_number");
$stmt->execute(array(':part_number' => $row['mpn']));
$row = $stmt->fetch(PDO::FETCH_BOTH);
$c=$row["price_each1"];// price for single item
for($i = 1; $i <= 8; $i++)
{
$b=$row["price_each".$i];
if ($b !=0.00)
{
$d=(($c-$b)/$c)*100;
$complete=$row[("price_break".$i)]. " ," .round($d)."%";
echo"</br>";
echo $complete;
echo"</br>";
}
}
echo "</span>";
echo "</td>";
//}
}
?>
</tr>
<table >
<tr >
<!-- <td ><?php //echo "Total purchases: ".$total."for part
number".$_POST["mpn"];?> </td> -->
<th class="basket2"> </th>
<th class="basket1"><?php echo "Total of £".$totpr;?> </th>
<th colspan="2" class="basket2"><?php echo "for ".$totqty." items";?>
</th>
<th class="basket3"> <img src="/stampede/images/scart.jpg"
alt="Shopping Cart" width="20"> </th>
</tr>
</table>
<?php
echo "</br>";
echo "</br>";
include ("order/options1.php");
?>
Solved. You have to pass variable via URL string to the new page.
I used the example below:
INSIDE "page1.php" or "page1.html"
// Send the variables myNumber=1 and myFruit="orange" to the new PHP page...
Send variables via URL!
INSIDE "page2c.php"
<?php
// Retrieve the URL variables (using PHP).
$num = $_GET['myNumber'];
$fruit = $_GET['myFruit'];
echo "Number: ".$num." Fruit: ".$fruit;
?>

PHP code not executing when javascript comes between

Here is the situation... Two results are created in the php page.. The results are echoed as json_encode . The results are showing perfectly. But when i insert a javascript code within two php code blocks, then one result is shown while the other is not.. I really have no idea why this is happening.. My code
$action = isset($_GET['action']);
if($action == "get_requests"){
include("../connect.php");
$sql_song_req = "SELECT COUNT(*) FROM `song_requests`";
$sql_select_song = "SELECT * FROM `song_requests` ORDER BY id ASC";
$sql_count = $rad->prepare($sql_song_req);
$sql_count->execute();
$count = $sql_count->fetchColumn();
$select_song_prep = $rad->prepare($sql_select_song);
$select_song_prep->execute();
while($row = $select_song_prep->fetch(PDO::FETCH_ASSOC)){
$id = $row['id'];
$name = $row['name'];
$song = $row['songname'];
$dedicatedto = $row['dedicatedto'];
?>
<script>
function delete_req(id){
alert("hello");
}
</script>
<?php
$data .= ' <tr cellpadding="5" cellspacing="6" align="center" width="60%">
<td>'.$id.'</td>
<td>'.$name.'</td>
<td>'.$song.'</td>
<td>'.$dedicatedto.'</td>
<td>Delete</td>
</tr>';
}
$display = ' <table "cellspacing="4" align="center">
<tr>
<th>ID</th>
<th>Name</th>
<th>Song</th>
<th>Dedicated to</th>
<th>Delete</th>
'.$data.'
</tr>
</table>';
$response = array();
$response['data_from_db'] = $display;
$response['count'] = $count;
echo json_encode($response);
}
Here the response['count'] is showing on my php page but not $response['data_from_db'].
And when I delete the javascript code then both of them are showing.. Help needed.
I should mention that am using NGINX and php5-fpm
You have a brace mismatch.
Add a brace } after $dedicatedto = $row['dedicatedto']; Your while loop wasn't properly closed.
$action = isset($_GET['action']);
if($action == "get_requests"){
include("../connect.php");
$sql_song_req = "SELECT COUNT(*) FROM `song_requests`";
$sql_select_song = "SELECT * FROM `song_requests` ORDER BY id ASC";
$sql_count = $rad->prepare($sql_song_req);
$sql_count->execute();
$count = $sql_count->fetchColumn();
$select_song_prep = $rad->prepare($sql_select_song);
$select_song_prep->execute();
while($row = $select_song_prep->fetch(PDO::FETCH_ASSOC)){
$id = $row['id'];
$name = $row['name'];
$song = $row['songname'];
$dedicatedto = $row['dedicatedto'];
} // <- added. Brace for while loop
?>
<script>
function delete_req(id){
alert("hello");
}
</script>
<?php
$data .= ' <tr cellpadding="5" cellspacing="6" align="center" width="60%">
<td>'.$id.'</td>
<td>'.$name.'</td>
<td>'.$song.'</td>
<td>'.$dedicatedto.'</td>
<td>Delete</td>
</tr>';
$display = ' <table "cellspacing="4" align="center">
<tr>
<th>ID</th>
<th>Name</th>
<th>Song</th>
<th>Dedicated to</th>
<th>Delete</th>
'.$data.'
</tr>
</table>';
$response = array();
$response['data_from_db'] = $display;
$response['count'] = $count;
echo json_encode($response);
}

Passing GET parameters in JediTable loadurl

Background:
I am creating a php generated shifts scheduler for my hospital's Operating Rooms. On X Axis I'm plotting days, on Y the ORs. I'm using Jeditable to edit in place each cell generating a dropdown from a select that load data.
Php Code:
$query = $db->query('select sp.id, sp.sigla from lista_specializzandi sp where sp.id not in (select sp.id from lista_specializzandi sp, esigenze e where sp.id = e.specializzando and e.giorno='.$giorno.' and (e.tipologia=2 or e.tipologia=3 or e.tipologia=4 or e.tipologia =5 or e.tipologia=6 or e.tipologia=7))');
$esiSelect = array();
while ($disp = $db->fetch_array($query)) {
$esiSelect[$disp['id']] = $disp['sigla'];
}
Javascript:
<script>
$(document).ready(function() {
$(".turnistica").editable('save_turnistica.php', {
data : <?php echo json_encode($esiSelect); ?>,
type : 'select',
indicator : 'Salvo...',
tooltip : 'Clicca per modificare',
placeholder : ' ',
onblur : 'submit',
event : 'click',
submitdata : function(value, settings) {
return {"giorno" : $(this).attr('id_giorno'), "sala" : $(this).parent().attr('id_riga')};
}
});
});
</script>
The table:
<section class="fluid" id="flip-scroll">
<table id="foglioEsigenze" class="table-bordered table-striped table-condensed cf full">
<col class="col10">
<?php
foreach ($cals as $c)
echo
'<col class="dw'.$c->isFeriale.$c->isFestivo.'"></col>';
?>
<thead class="cf verde_trasp bold text-white">
<tr>
<th class="col1"> </th>
<?php
foreach ($cals as $c)
echo
'<th class="dw'.$c->isFeriale.$c->isFestivo.'"><span style="font-size:9px">'.substr($c->giornoNome, 0, 3).'</span> '.$c->d.'</th>';
?>
</tr>
</thead>
<tbody>
<?php
while ($s = $db->fetch_array($indice)) {
echo
'<tr class="Row" data-blocco="'.$s['blocco'].'" id_riga="'.$s['id'].'"><td style="text-align: left;">'.$s['sigla'].'</td>';
foreach ($cals as $g) {
echo
'<td class="turnistica" style="text-align: center;" id_giorno="'.$g->id.'">';
global $db;
$sql = 'select sp.sigla from turnistica t, lista_specializzandi sp where t.giorno = '.$g->id.' and t.riga='.$s['id'].' and t.specializzando = sp.id limit 1';
$query = $db->query($sql);
$sigla = $db->fetch_array($query);
echo $sigla['sigla'];
'</td>';
'</tr>';
}
}
?>
</tbody>
</table>
</section>
... So far so good!
Now I need to create a dropdown that auto remove physicians after I insert them in a column.
I thought this solution but I don't know why it's not working.
1) I moved all the load code to an external php file:
<?php
require ('includes/initialise.php');
global $db;
$giorno = $_GET['giorno'];
$query = $db->query('select sp.id, sp.sigla from lista_specializzandi sp where sp.id not in (select sp.id from lista_specializzandi sp, esigenze e where sp.id = e.specializzando and e.giorno='.$giorno.' and (e.tipologia=2 or e.tipologia=3 or e.tipologia=4 or e.tipologia =5 or e.tipologia=6 or e.tipologia=7))');
$esiSelect = array();
while ($disp = $db->fetch_array($query)) {
$esiSelect[$disp['id']] = $disp['sigla'];
}
echo json_encode($esiSelect);
?>
2) I called it by loadurl in the javascript adding the attribute of the element
loadurl : "disponibili.php?giorno=" + $(this).attr("id_giorno"),
All the problems are coming from the Javascript variable I am passing. But I googled a lot without solving the problem.
How can I fix this?
#dcaswell: I am not able to pass the javascript variable in 2) to the loadurl file, so no action can be performed before populating the json list. I am definitely missing something. Any help would be much appreciated.
Thanks

Categories

Resources