I created a table showing the student's name and nis. How do I enter the value in each form and display the sum in the n.akhir form? I want if you click the save button, the summation will be processed and entered into the database.
I have tried several times but always failed
<table class="table table-hover">
<tr>
<th>No</th>
<th>NAMA</th>
<th>UH 1</th>
<th>UH 2</th>
<th>UH 3</th>
<th>UH 4</th>
<th>N.AKHIR</th>
</tr>
<?php foreach ($siswa as $row){
echo "<tr> <td width='100'>$row->nis</td>
<td>". strtoupper($row->nama)."</td>
<td width='150'><input type='int' id='ulangan_1".$row->nis."' class='form-control'></td>
<td width='150'><input type='int' id='ulangan_2".$row->nis."' class='form-control'></td>
<td width='150'><input type='int' id='ulangan_3".$row->nis."' class='form-control'></td>
<td width='150'><input type='int' id='ulangan_4".$row->nis."' class='form-control'></td>
<td width='150'><input type='int' id='nilai_akhir".$row->nis."' class='form-control'></td>
</tr>";
} ?> </table>
and here the javascript
$('#btn_save').on('click',function(nis){
var ulangan_1 = $('#ulangan_1'+nis).val();
var ulangan_2 = $('#ulangan_2'+nis).val();
var ulangan_3 = $('#ulangan_3'+nis).val();
var ulangan_4 = $('#ulangan_4'+nis).val();
var nilai_akhir = ulangan_1 + ulangan_2 + ulangan_3 + ulangan_4 / 4;
$("#nilai_akhir"+nis).val(nilai_akhir);
$.ajax({
type : "POST",
url : "<?php echo site_url('index.php/nilai/update_nilai')?>",
dataType : "JSON",
data : {nis:nis , jadwal:<?php echo $this->uri->segment(3)?>, ulangan_1:ulangan_1, ulangan_2:ulangan_2, ulangan_3:ulangan_3, ulangan_4:ulangan_4,nilai_akhir:nilai_akhir},
success: function(data){
//$("#dataSiswa").html(html);
}
});
return false;
});
Related
I have a table which shows the list of my products and I have used jQuery to delete products without reloading the page, however the updated table doesn't show unless I refresh the page..
I have tried to hide it by using opacity, still it doesn't work..
Here is my php code
<div class="table-stats order-table ov-h">
<table id="bootstrap-data-table" class="table ">
<thead>
<tr>
<th>Image</th>
<th>Name</th>
<th>Availability</th>
<th>Category</th>
<th>Total Ordered</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody id="data-table">
<?php
$stmt_1 = mysqli_prepare($link,"SELECT * FROM products");
mysqli_stmt_execute($stmt_1);
$result = mysqli_stmt_get_result($stmt_1);
while($row = mysqli_fetch_array($result)){ ?>
<div class="product">
<tr class="product">
<?php
$sql_img = "SELECT * FROM pro_images WHERE pro_id= ? LIMIT ?";
$stmt_img = mysqli_prepare($link, $sql_img);
mysqli_stmt_bind_param($stmt_img, "ii" ,$param_pro_id, $param_limit);
$param_pro_id = $row["pro_id"];
$param_limit = 1;
mysqli_stmt_execute($stmt_img);
$img_results = mysqli_stmt_get_result($stmt_img);
$image = mysqli_fetch_assoc($img_results);
?>
<td><img src="../admin/assets/img/products/<?php echo $image["pro_image"]; ?>"></td>
<td><?php echo $row["pro_name"]; ?></td>
<td><?php echo $row["pro_quantity"]; ?></td>
<?php
$sql_category = "SELECT cat_name FROM categories WHERE cat_id = ?";
$stmt_category = mysqli_prepare($link, $sql_category);
mysqli_stmt_bind_param($stmt_category, "i", $param_cat_id);
$param_cat_id = $row["pro_category"];
mysqli_stmt_execute($stmt_category);
$result_category = mysqli_stmt_get_result($stmt_category);
$category = mysqli_fetch_assoc($result_category);
?>
<td> <?php echo $category["cat_name"]; ?> </td>
<?php
$pro_ord = "SELECT COUNT(*) AS total FROM order_details WHERE pro_id = ?";
$pro_stmt = mysqli_prepare($link, $pro_ord);
mysqli_stmt_bind_param($pro_stmt ,"i", $row["pro_id"]);
mysqli_stmt_execute($pro_stmt);
$pro_res = mysqli_stmt_get_result($pro_stmt);
$pro = mysqli_fetch_array($pro_res);
?>
<td><?php echo $pro["total"]; ?></td>
<td><span class="badge badge-success"><i class="ti-pencil"></i></span>
</td>
<td>
<button class="remove badge badge-danger" onclick="delete_data(<?php echo $row["pro_id"]; ?>)"><i class="ti-trash"></i></button>
</td>
</tr>
</div>
<?php } ?>
</tbody>
</table>
</div>
And here is my JQUERY code
function delete_data(d){
var id=d;
if (confirm("Are you sure you want to delete this product? This cannot be undone later.")) {
$.ajax({
type: "post",
url: "products.php",
data: {id:id},
success: function(){
$(this).parents(".product").animate("fast").animate({ opacity : "hide" }, "slow");
}
});
}
}
And here is the delete code
$pro_id =$_POST['id'];
$delete = "DELETE FROM products WHERE pro_id= ?";
$results = mysqli_prepare($link, $delete);
mysqli_stmt_bind_param($results, "i", $param_pro_id);
$param_pro_id = $pro_id;
mysqli_stmt_execute($results);
You need to be more specific when you targeting the div you want to refresh, for example:
success: function(){
$("#div_id_you_want_refresh")
.load("your_entire_url" + "#div_id_you_want_refresh");
}
You can pass this as well inside your delete_data function where this refer to current element clicked i.e : your button . Then , inside success function use this to hide your .product element.
Demo Code:
function delete_data(d, el) {
var id = d;
if (confirm("Are you sure you want to delete this product? This cannot be undone later.")) {
/* $.ajax({
type: "post",
url: "products.php",
data: {
id: id
},
success: function() {*/
//use this then remove closest product tr
$(el).closest(".product").animate("fast").animate({
opacity: "hide"
}, "slow");
/* }
});*/
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="bootstrap-data-table" class="table">
<thead>
<tr>
<th>Image</th>
<th>Name</th>
<th>Availability</th>
<th>Category</th>
<th>Total Ordered</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody id="data-table">
<tr class="product">
<td><img src="../admin/assets/img/products/"></td>
<td>
smwthing
</td>
<td>
1
</td>
<td>
abs
<td>
1222
</td>
<td><span class="badge badge-success"><i class="ti-pencil"></i></span>
</td>
<td>
<!--pass `this` inside fn-->
<button class="remove badge badge-danger" onclick="delete_data('1',this)"><i class="ti-trash">x</i></button>
</td>
</tr>
<tr class="product">
<td><img src="../admin/assets/img/products/"></td>
<td>
smwthing
</td>
<td>
12
</td>
<td>
abs1
<td>
12221
</td>
<td><span class="badge badge-success"><i class="ti-pencil"></i></span>
</td>
<td>
<button class="remove badge badge-danger" onclick="delete_data('2',this)"><i class="ti-trash">x</i></button>
</td>
</tr>
</tbody>
</table>
Just try to make it simple.
I'm trying to show data in my data table when I click a dropdown value
I'm using ajax to get the data from my controller
everything works fine except the results isn't showing in my view even the status code shows 200 ok
here's my Model
function tampil_renja(){
$this->db->distinct();
$this->db->select
(
'lkp_program.progskpd_id AS prog_id,
CONCAT(msr_mstrurusan.uru_kode, '.', lkp_program.progskpd_kode) AS prog_kode,
lkp_program.progskpd_prog_uraian as prog_uraian');
$this->db->from('msr_mstrurusan');
$this->db->join('lkp_program', 'msr_mstrurusan.uru_id = lkp_program.progskpd_ursid');
$this->db->join('lkp_kegiatan', 'lkp_program.progskpd_id = lkp_kegiatan.kegskpd_prog_id');
$this->db->join('mnv_keg_renja', 'lkp_kegiatan.kegskpd_id = mnv_keg_renja.tar_keg_id');
$this->db->where('mnv_keg_renja.tar_keg_id is NOT NULL', NULL, FALSE);
$this->db->order_by("lkp_program.progskpd_id", "asc");
return $this->db->get();
}
here's my ajax code within the view
<div class="container-fluid">
<header>
<h3 class="mb-2">Renja</h3>
</header>
<div class="card-body">
<div class="table-responsive" style="margin-bottom: 1px;">
<?php
if (count($skpd) > 0) {
?>
<label class="col-sm-1 control-label">OPD</label>
<div class="col-sm-5">
<select id="skpd" name="skpd" class="form-control input-sm">
<option value="0">-- Pilih Perangkat Daerah--</option>
<?php
foreach ($skpd as $pd) {
echo "<option value='" . $pd->uk_kowil . "#" . $pd->uk_id . "'>" . strtoupper($pd->uk_nama) . "</option>";
}
?>
</select>
</div>
<?php
}
else {
?>
<input type='hidden' name='skpd' id='skpd' value='<?php
?>' />
<?php
}
?>
<div id="listskpd" class="col-sm-1">
<i id="rldspin" style="margin-top:5px"></i>
</div>
<div id="jml_angg" class="text-right" style="padding-top: 8px;font-size: 13px;margin-right: 15px;">
</div>
</div>
<table id="list_target" class="table table-striped table-bordered table-hover" width="100%">
<thead>
<tr>
<th rowspan="3" class="text-center text-middle" style="width:1%;">No</th>
<th rowspan="3" class="text-center text-middle" style="width:4%;">Kode Rekening</th>
<th rowspan="3" class="text-center text-middle" style="width:27%;">Program/Kegiatan</th>
<th rowspan="3" class="text-center text-middle" style="width:20%;">Indikator Kinerja program (outcome)/ kegiatan (output) </th>
<th colspan="7" class="text-center text-middle" style="width:30%;">Target Renja [berdasarkan DPA] SKPD pada Tahun</th>
</tr>
<tr>
<th rowspan="2" class="text-center text-middle" style=""> Satuan</th>
<th colspan="2" class="text-center text-middle" style="">Target Triwulan 1</th>
<th colspan="2" class="text-center text-middle" style="">Target Triwulan 2</th>
<th colspan="2" class="text-center text-middle" style="">Target Triwulan 3</th>
<th colspan="2" class="text-center text-middle" style="">Target Triwulan 4</th>
<th rowspan="2" class="text-center text-middle" style="">Target Anggaran</th>
</tr>
<tr>
<th class="text-center text-middle" style="">Kin</th>
<th class="text-center text-middle" style="">Keu</th>
<th class="text-center text-middle" style="">Kin</th>
<th class="text-center text-middle" style="">Keu</th>
<th class="text-center text-middle" style="">Kin</th>
<th class="text-center text-middle" style="">Keu</th>
<th class="text-center text-middle" style="">Kin</th>
<th class="text-center text-middle" style="">Keu</th>
</tr>
</thead>
<tbody id="datatarget">
</tbody>
</table>
</div>
</div>
</article>
<script type="text/javascript" language="javascript" src="<?php echo base_url().'assets/vendor/jquery/jquery.js'?>"></script>
<script type="text/javascript" language="javascript" src="<?php echo base_url().'assets/vendor/datatables/jquery.dataTables.js'?>"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#skpd').change(function(){
var arrval = $(this).val().split("#");
var kowil = arrval[0];
var idpd = arrval[1];
if(idpd != 0){;
tampil_data_renja(kowil, idpd);
} else {
$('#datatarget').DataTable.Destroy();
$('#datatarget').DataTable.Draw();
$('#datatarget').DataTable.Destroy();
}
});
function tampil_data_renja(kowil, idpd){
$.ajax({
type : 'ajax',
url : '<?php echo base_url()?>renja/tampil_renja/',
async : false,
dataType : 'json',
success : function(data){
var html = '';
var i;
alert(data.length);
for(i=0; i<data.length; i++){
html += '<tr>'+
'<td>'+(i+1).toString()+'</td>'+
'<td>'+data[i].prog_kode+'</td>'+
'<td>'+data[i].prog_uraian+'</td>'+
'</tr>';
}
$('#datatarget').html(html);
},
error: function(){
alert('Could not load the data');
}
});
}
and this is the controller
function tampil_renja(){
echo json_encode( $this->m_data->tampil_renja()->result() );
}
JSON result in the network tab of chrome dev tools
[{"prog_id":"1","prog_kode":"6.01.0118","prog_uraian":"Program Koordinasi, pembinaan dan penyelenggaraan pemerintahan, ketentraman dan ketertiban umum, perekonomian, kesejahteraan sosial dan pembangunan"},{"prog_id":"2","prog_kode":"6.01.0118","prog_uraian":"Program Koordinasi, pembinaan dan penyelenggaraan pemerintahan, ketentraman dan ketertiban umum, perekonomian, kesejahteraan sosial dan pembangunan"}]
any help and guide would be appreciated
sorry for my bad english by the way
Please try the following code:
Changes made are:
commented datatype in the AJAX
parse response of success function as JSON.
$.ajax({
type : 'get', // edit 1
url : '<?php echo base_url()?>renja/tampil_renja/',
async : false,
//dataType : 'json', //change over here
success : function(data){
data = JSON.parse(data); //change over here
var html = '';
var i;
alert(data.length);
for(i=0; i<data.length; i++){
html += '<tr>'+
'<td>'+(i+1).toString()+'</td>'+
// '<td>'+data[i].prog_id+'</td>'+
'<td>'+data[i].prog_kode+'</td>'+
'<td>'+data[i].prog_uraian+'</td>'+
'</tr>';
}
$('#datatarget').html(html);
},
error: function(){
alert('Could not load the data');
}
})
You have to redraw the datatable after the element is updated on ajax call success :
//fungsi tampil barang
function tampil_data_renja(kowil, idpd){
// var requrl = '<?php echo base_url()?>renja/tampil_renja/'+kowil+'/'+idpd;
$.ajax({
type : 'ajax',
// url : '<?php echo base_url()?>renja/tampil_renja/'+kowil+'/'+idpd,
url : '<?php echo base_url()?>renja/tampil_renja/',
async : false,
dataType : 'json',
success : function(data){
var html = '';
var i;
// console.log(data.length);
alert(data.length);
for(i=0; i<data.length; i++){
html += '<tr>'+
'<td>'+(i+1).toString()+'</td>'+
// '<td>'+data[i].prog_id+'</td>'+
'<td>'+data[i].prog_kode+'</td>'+
'<td>'+data[i].prog_uraian+'</td>'+
'</tr>';
}
$('#datatarget').html(html);
$('#list_target').DataTable.Draw(); // redraw the datatable
},
error: function(){
alert('Could not load the data');
}
});
// return alert(kowil);
}
My app is reading information from a database and shows the information to the user using jQuery. If a user clicks on an entry, a div will popup and shows more information.
I want to open these div with a URL. Is it possible? I'm thinking about to use the entry id as a parameter?
Like this: div with entry id = 123 will open a link like this
https://url.de/index.php?param=123
// *** Funktion für Details-Overlay ***
function on(id) {
$.ajax({
url: "AJAX.php",
data: 'id=' + id + '&switch_content=details',
success: function(result) {
$("#data-table").html(result);
}
});
document.getElementById("overlay").style.display = "block";
}
function off() {
document.getElementById("overlay").style.display = "none";
}
#overlay {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id=12>Click on me</div>
<!-- OVERLAY -->
<div id="overlay">
<div id="ContainerBox" align="center">
<img onclick="off()" id="imgclose" src="images/auswertung-close.png">
<div id="headerSticky"></div>
<h2>Gesamte Übersicht</h2>
<hr>
<!-- Tabelle für Detailseite -->
<table data-role="table" id="data-table" data-filter="true" data-input="#filterTable-input" class="ui-responsive" border="1" style="overflow-x: auto;">
<!-- AJAX/Informations -->
</table>
</div>
</div>
PHP/AJAX:
<?php
// Verbindung zur Datenbank
$pdo = new PDO('mysql:host=***;dbname=***', '***', '***');
$pdo ->exec("set names utf8");
if ($_GET ['switch_content']=='details'){
// SQL Befehl + ID rausnehmen
$sql_befehlDetail = "SELECT * FROM fair_contact_form WHERE id= :id";
// Ergebnisse aus dem SQL Befehl in $ergebnis ziehen
$ergebnisDetail = $pdo->prepare ($sql_befehlDetail);
$ergebnisDetail->execute(array('id'=>$_GET['id']));
$datenDetail = $ergebnisDetail->fetch();
$search = '/../../../../htdocs/..;
$replace = 'https://url.de';
$karte = str_replace($search, $replace, $datenDetail['businessCard']);
echo '<thead>
<tr>
<td class="" colspan="2"></td>
</tr>
</thead>
<tbody>
<tr>
<td data-priority="2"> ID </td>
<td> '. $datenDetail['id'] .' </td>
</tr>
<tr>
<td data-priority="2"> Handelsmesse </td>
<td> '. $datenDetail['fair'] .' </td>
</tr>
<tr>
<td data-priority="3"> Datum </td>
<td> '. $datenDetail['timestamp'] .' </td>
</tr>
<tr>
<td data-priority="4"> dateTimeOfContact: </td>
<td> '. $datenDetail['dateTimeOfContact'] .' </td>
</tr>
<tr>
<td data-priority="5"> Gesprächsdauer </td>
<td> '. $datenDetail['durationOfContact'] .' </td>
</tr>
</tbody>';
}
else if($_GET['switch_content']=='startseite') {
$sql_befehlGesamt = "SELECT * FROM fair_contact_form ORDER BY id DESC";
$ergebnisGesamt = $pdo->query($sql_befehlGesamt);
?><div data-role="header"></div>
<div role="main" class="ui-content">
<table id="table" border="1" data-filter="true" data-input="#filterTable-input" class="ui-responsive" data-role="table"
id="table-column-toggle" data-mode="columntoggle" class="ui-responsive table-stroke">
<thead>
<tr>
<th data-priority="1" id="sortieren_id">ID</th>
<th data-priority="4" id="sortieren_email" class="ui-table-cell-hidden">E-Mail</th>
<th data-priority="4" id="sortieren_gespraechsinhalt" class="ui-table-cell-hidden">Gesprächsinhalt</th> <!-- classe dient dazu, checkbox auf unchecked zu stellen -->
</tr>
</thead>
<tbody><?php
while ($datenGesamt = $ergebnisGesamt->fetchObject()) {
$dateTimeOfContact = new DateTime($datenGesamt->dateTimeOfContact);
?><tr onclick="on(<?=$datenGesamt->id?>)" style="cursor:pointer">
<td onclick="on(<?=$datenGesamt->id ?>)"><p style="color:#E3000F;"><b><?=$datenGesamt->id ?></b></p></td>
<td><?=$datenGesamt->fair ?></td>
<td><?=$dateTimeOfContact->format('d.m.Y') ?></td>
<td><?=$datenGesamt->author ?></td>
<td><?=$datenGesamt->genderOfContact ?></td>
<td><?=$datenGesamt->nameOfContact ?></td>
<td><?=$datenGesamt->surnameOfContact ?></td>
<td class="ui-table-cell-hidden"><?=$datenGesamt->companyName ?></td>
</tr><?php
} ?>
</tbody>
</table>
</div>
The information in the Ajax div should be reachable with a URL+parameter.
Yes, you can trigger the desired id details on start.
Just add next code to your js file:
// Shorthand for $( document ).ready()
$(function() {
// This code will be run when document will be loaded
var args = window.location.search.substring(1); // Get all URL arg
args = args.split('&').map(arg => arg.split('=')); // convert to array with key, value
args.forEach(function(arg) {
var key = arg[0];
var val = arg[1];
if (key === 'param') { // Check if the URL param is our param, and if yes - open popup
on(val);
}
});
});
I'm displaying a table with AJAX in my website. I wrote a JQuery code for sorting my table when it's send via AJAX and a <th>-tag is clicked. (I don't want to use a plugin. No, really, I don't want to use a plugin!)
This is my code:
PHP (index.php):
<form action="query.php" method="get">
<input type="search" name="query" autofocus="true" autocomplete="off" list="products">
<datalist id="products">
<?php
$sql = "SELECT * FROM products;";
$result = mysqli_query($con, $sql);
while ($product = mysqli_fetch_array($result)) {
echo "<option value=\"" . $product["productname"] . "\">" . $product["price"] . " $</option>";
}
?>
</datalist>
<button type="submit">Search</button>
</form>
<div class="result" align="center"></div>
PHP (query.php):
<?php
include_once "connection.php";
$query = trim($_GET["query"]);
$query = mysqli_real_escape_string($con, $query);
$sql = "SELECT * FROM products WHERE productname LIKE '%$query%' ORDER BY productname;";
$result = mysqli_query($con, $sql);
$result_no = mysqli_num_rows($result);
if ($result_no > 0) {
echo "<table>";
echo "<thead>";
echo "<tr>";
echo "<th>Product</th>";
echo "<th>Price</th>";
echo "<th>Quantity</th>";
echo "</tr>";
echo "</thead>";
echo "<tbody>";
while ($product = mysqli_fetch_array($result)) {
echo "<tr class=\"table\"><td align=\"left\">" . $product["productname"] . "</td><td align=\"right\">" . $product["price"] . " $</td><td align=\"right\">" . $product["quantity"] . "</td></tr>";
}
echo "</tbody>";
echo "<tfoot>";
if ($result_no == 1) {
echo "<tr><td colspan=\"3\" align=\"center\">" . $result_no . " product found." . "</td></tr>";
} else {
echo "<tr><td colspan=\"3\" align=\"center\">" . $result_no . " product found." . "</td></tr>";
}
echo "</tfoot>";
echo "</table>";
} elseif ($result_no <= 0) {
echo "<p>No products found.</p>";
}
mysqli_close($con);
?>
JQuery:
$(document).ready(function() {
$("form").on("submit", function(event) {
event.preventDefault();
var form = $(this);
$.ajax({
type: this.method,
url: this.action,
data: form.serialize(),
cache: false,
success: function(data) {
$("div.result").html(data);
$("th").on("click", function() {
var column = $(this).index();
var tbody = $("tbody");
var rows = tbody.find("tr");
var dir = $(this).data("dir") || -1;
dir *= -1;
rows.sort(function(a, b) {
var aVal = $($(a).find("td")[column]).text().toLowerCase();
var bVal = $($(b).find("td")[column]).text().toLowerCase();
return aVal > bVal ? 1 * dir : aVal < bVal ? -1 * dir : 0;
});
$(this).data("dir", dir);
tbody.empty();
$(rows).appendTo(tbody);
});
}
});
});
});
The connection.php is for connecting to my database. I use MySQL and PHPMyAdmin. My tables are 'users' for login data and 'products' for the shop products.
My Problem: The first line of the table is alway sorted at the wrong place.
Use the built in javascript sort function.
I extracted the relevant sort code from your example
I grabbed a sample table from w3cschools
I modified the js to store the sorted direction in the header cell.
I implemented a compare function (see linked sort documentation).
I replaced the tbody when the sort was complete.
EDIT: changed out HTML, added functionality to function to enable numeric sorting and not just alphabetically. Note the number class and the new if in the sort function
$("th").on("click", function() {
var column = $(this).index();
var numeric = $(this).hasClass("number"); //this class has been sprinkled to identify numeric sort.
var bdy = $(this).closest("table").find("tbody");
var rows = bdy.find("tr");
var dir = $(this).data("dir") || -1; //default direction is desc
dir *= -1; //reverse the stored direction
rows.sort(function(a, b) {
var aVal = $($(a).find("td")[column]).text().toLowerCase(); //get the text from one row
var bVal = $($(b).find("td")[column]).text().toLowerCase(); //get the text from row 2
if (numeric) { //added to handle numeric columns
aVal = parseFloat(aVal);
bVal = parseFloat(bVal);
}
return aVal > bVal ? 1 * dir : aVal < bVal ? -1 * dir : 0; // note the dir value to change direction
}); //sort the rows by the column content
bdy.empty(); //empty the body
$(rows).appendTo(bdy); //put the rows back
$(this).data("dir", dir); //log the direction
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table">
<thead>
<tr class="table">
<th class="table">Product</th>
<th class="table number">Price</th>
<th class="table number">Quantity</th>
</tr>
</thead>
<tbody>
<tr class="table">
<td align="left" class="table">Chainsaw</td>
<td align="right" class="table">60.00 $</td>
<td align="right" class="table">1</td>
</tr>
<tr class="table">
<td align="left" class="table">Hammer</td>
<td align="right" class="table">24.99 $</td>
<td align="right" class="table">2</td>
</tr>
<tr class="table">
<td align="left" class="table">Nails (25 per Box)</td>
<td align="right" class="table">9.99 $</td>
<td align="right" class="table">21</td>
</tr>
<tr class="table">
<td align="left" class="table">Screwdriver</td>
<td align="right" class="table">29.99 $</td>
<td align="right" class="table">2</td>
</tr>
<tr class="table">
<td align="left" class="table">Screws (25 per Box)</td>
<td align="right" class="table">15.00 $</td>
<td align="right" class="table">26</td>
</tr>
</tbody>
<tfoot>
<tr class="table">
<td colspan="3" align="center" class="table">5 products found.</td>
</tr>
</tfoot>
</table>
#FelixRewer, please include a sample rendered table, your question was updated with your PHP. I believe that the PHP is not your problem but the HTML that comes out the other end.
Yes, maybe you're right. So here's a code snippet with the output of query.php and the JQuery tablesorter (I also added my styles, I don't think it's relevant, but if yes, here it is.):
$("th").on("click", function() {
var column = $(this).index();
var table = $("table");
var tbody = table.find("tbody");
var rows = tbody.find("tr");
var dir = $(this).data("dir") || -1;
dir *= -1;
rows.sort(function(a, b) {
var aVal = $($(a).find("td")[column]).text().toLowerCase().trim();
var bVal = $($(b).find("td")[column]).text().toLowerCase().trim();
return aVal > bVal ? 1 * dir : aVal < bVal ? -1 * dir : 0;
});
$(this).data("dir", dir);
tbody.empty();
$(rows).appendTo(table);
});
.table {
margin: 3vmax;
border: 1px solid #000000;
border-collapse: collapse;
color: #000000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table">
<thead>
<tr class="table">
<th class="table">Product</th>
<th class="table">Price</th>
<th class="table">Quantity</th>
</tr>
</thead>
<tbody>
<tr class="table">
<td align="left" class="table">Chainsaw</td>
<td align="right" class="table">60.00 $</td>
<td align="right" class="table">1</td>
</tr>
<tr class="table">
<td align="left" class="table">Hammer</td>
<td align="right" class="table">24.99 $</td>
<td align="right" class="table">2</td>
</tr>
<tr class="table">
<td align="left" class="table">Nails (25 per Box)</td>
<td align="right" class="table">9.99 $</td>
<td align="right" class="table">21</td>
</tr>
<tr class="table">
<td align="left" class="table">Screwdriver</td>
<td align="right" class="table">29.99 $</td>
<td align="right" class="table">2</td>
</tr>
<tr class="table">
<td align="left" class="table">Screws (25 per Box)</td>
<td align="right" class="table">15.00 $</td>
<td align="right" class="table">26</td>
</tr>
</tbody>
<tfoot>
<tr class="table">
<td colspan="3" align="center" class="table">5 products found.</td>
</tr>
</tfoot>
</table>
And yes I have the same problem here. I've tested a lot with my code and I think maybe the first line gets sorted at the wrong place, because of the <tfoot>, but that's just an assumption.
This topic is closed. Here's the code I was looking for:
JavaScript: https://jsfiddle.net/tf4e97w6/#&togetherjs=TGIj8qdzUO
jQuery: https://jsfiddle.net/15ke8Lqv/#&togetherjs=DACQV5mE9F
Code snippet:
$(document).ready(function() {
$("th").on("click", function() {
var column = $(this).index();
var table = $("table");
var tbody = table.find("tbody");
var rows = tbody.find("tr");
var dir = $(this).data("dir") || -1;
dir *= -1;
$(this).siblings().data("dir", -1);
rows.sort(function(a, b) {
var aVal = $($(a).find("td")[column]).html().toLowerCase().trim();
var bVal = $($(b).find("td")[column]).html().toLowerCase().trim();
if ($.isNumeric(aVal.charAt()) && $.isNumeric(bVal.charAt())) {
aVal = parseFloat(aVal);
bVal = parseFloat(bVal);
}
return aVal > bVal ? 1 * dir : aVal < bVal ? -1 * dir : 0;
});
$(this).data("dir", dir);
tbody.empty();
$(rows).appendTo(table);
});
});
h1 {
color: #cc1100;
}
table {
width: 100%;
}
table,
tr,
td {
border: 1px solid #000000;
border-collapse: collapse;
}
tfoot,
thead {
text-align: center;
background-color: #cccccc;
}
th:hover {
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<caption>
<h1>Tablesorter</h1>
</caption>
<thead>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
</thead>
<tbody>
<tr>
<td>January</td>
<td>$150</td>
</tr>
<tr>
<td>February</td>
<td>$160</td>
</tr>
<tr>
<td>March</td>
<td>$240</td>
</tr>
<tr>
<td>April</td>
<td>$160</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="2">Sum: $710</td>
</tr>
</tfoot>
</table>
With kind regards,
Felix Rewer.
I have number of rows in a table fetched from database. I need to display output of each row beside dat table only. output data also fetching from database.
Example: If i click first row means i want detail information about that row next to that table.
<script type="text/javascript">
$(function() {
$('#showmenu').click(function() {
$(".menu").slideToggle();
});
});
</script>
PHP Code: First Table(Displaying Data)
$query = "select * from orders_list";
$result = mysql_query($query);
$num_rows = mysql_num_rows($result);
if($num_rows >= 1)
{
echo "<div id='showmenu' class='scroll'>";
echo "<table id='table_struct' cellspacing='0' cellpadding='1' border='1' width='400'>
<tr class='tr_class' bgcolor='#0066CC'>
<td align='center' style='font-weight:bold'> Select </td>
<td align='center' style='font-weight:bold'> order_id </td>
<td align='center' style='font-weight:bold'> customer_name </td>
<td align='center' style='font-weight:bold'> no_of_pack </td>
<td align='center' style='font-weight:bold'> price </td>
<td align='center' style='font-weight:bold'> Weight </td>
<td align='center' style='font-weight:bold'> payment mode </td>
</tr>";
while($row = mysql_fetch_array($result))
{
$order_id = $row['order_id'];
echo "<tr>
<td align='center'><input type='checkbox' class='case' name='case' value='1'></td>
<td align='center'>".$row['order_id']."</td>
<td align='center'>".$row['customer_name']."</td>
<td align='center'>".$row['number_of_pack']."</td>
<td align='center'>".$row['price']."</td>
<td align='center'>".$row['weight']."</td>
<td align='center'>".$row['payment']."</td>";
echo "</tr>";
}
echo "</table>";
echo "</div>";
}
code for output to display in same page:
$_SESSION['order_id'] = $order_id;
echo $_SESSION['order_id'];
$query = "select * from orders_details where order_id=$order_id";
$result = mysql_query($query);
$num_rows = mysql_num_rows($result);
if($num_rows >= 1)
{
echo "<div class='menu' class='scroll'>";
echo "<table id='table_struct' cellspacing='0' cellpadding='1' border='1' width='400'>
<tr class='tr_class' bgcolor='#0066CC'>
<td align='center' style='font-weight:bold'> Product </td>
<td align='center' style='font-weight:bold'> Quantity </td>
<td align='center' style='font-weight:bold'> Sku </td>
<td align='center' style='font-weight:bold'> Price </td>
<td align='center' style='font-weight:bold'> Total </td>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>
<td align='center'><input type='checkbox' class='case' name='case' value='1'></td>
<td align='center'>".$row['product']."</td>
<td align='center'>".$row['quantity']."</td>
<td align='center'>".$row['sku']."</td>
<td align='center'>".$row['price']."</td>
<td align='center'>".$row['total']."</td>";
echo "</tr>";
}
echo "</table>";
echo "</div>";
}
Pls help me out..
There are two solutions one is to create row next to each row with $order_id and inside you include your second script. You also hide that row with style="display:none" and then in javascript you hide or show next row (you can inslude whole table in one td with colspan="7")
$('#table_struct tr.input').click(function() {
$(this).next().toggle();
});
Second option is to have your second script in different file and run ajax request with order_id of selected row. You can display that second table inside dialog box. Or if you want it to be next to the row then you can set postion of it using javascript:
$('#table_struct tr').click(function() {
var $this = $(this);
var offset = $this.offset();
var height = $this.height();
var order_id = $this.data('order_id');
$('.menu').remove();
$.get('your_second_script.php?order_id=' + order_id, function(table) {
$('#showmenu').append(table);
$('.menu').css({
position: 'absolute',
left: offset.left,
top: offset.top+height
});
});
});
tr will need to have data-order_id attribute.
You may find something like this-
In your first table
<tr class='tr_class' bgcolor='#0066CC' data-id="<?=$row['order_id']?>">
Your jQuery-
$('#tr_class').click(function(){
var rowId = $(this).data('id');
$.ajax({
url: "targetScript.php",
data:{rowId: rowId},
type: 'POST',
success: function(data){
$('#table_second').html("");
$('#table_second').html(data);
}
});
});
targetScript.php -
<?php
if(isset($_POST['rowId'])){
$order_id = $_POST['rowId'];
$query = "select * from orders_details where order_id=$order_id";
$result = mysql_query($query);
$num_rows = mysql_num_rows($result);
$html = "";
if($num_rows >= 1){
$html.="<tr class='tr_class' bgcolor='#0066CC'>
<td align='center' style='font-weight:bold'> Product </td>
<td align='center' style='font-weight:bold'> Quantity </td>
<td align='center' style='font-weight:bold'> Sku </td>
<td align='center' style='font-weight:bold'> Price </td>
<td align='center' style='font-weight:bold'> Total </td>
</tr>";
while($row = mysql_fetch_array($result)){
$html.="<tr>
<td align='center'><input type='checkbox' class='case' name='case' value='1'></td>
<td align='center'>".$row['product']."</td>
<td align='center'>".$row['quantity']."</td>
<td align='center'>".$row['sku']."</td>
<td align='center'>".$row['price']."</td>
<td align='center'>".$row['total']."</td>"."</tr>";
}
}print $html;
}
?>