Inserting each .post data into a <td> using .each - php

I was wondering if this is possible to be done with jQuery. Please see following code.
HTML
<table id="order">
<tr>
<td class="order_items"></td>
<td class="order_items"></td>
<td class="order_items"></td>
<td class="order_items"></td>
<td class="order_items"></td>
<td class="order_items"></td>
</tr>
<tr>
<td class="order_items"></td>
<td class="order_items"></td>
<td class="order_items"></td>
<td class="order_items"></td>
<td class="order_items"></td>
<td class="order_items"></td>
</tr>
<tr>
<td class="order_items"></td>
<td class="order_items"></td>
<td class="order_items"></td>
<td class="order_items"></td>
<td class="order_items"></td>
<td class="order_items"></td>
</tr>
</table>
javascript
$(document).ready(function(){
$("td.load_ads").each(function(){
$(this).html("Place a New Ad Free!");
});
var count=$("td.load_ads").length; //18
$.post('/fetch_orders.php',{count:count},function(data){
var data_arr=data.split('/end');
for(index=0;index < data_arr.length;index++){ //for each of the array values got back from fetch orders.php
.
..
... Stuck here. How to make each data_arr(ie: each data_arr[index]) go into each td?
.POST script
$count =$_POST['count'];
$query="SELECT * FROM orders1_manager_orders ORDER BY RAND() LIMIT $count";
$db->setQuery($query);
$ads=$db->loadRowList();
foreach($ads as $ads_to_display){
echo $orders_to_display[9].'/';
echo $orders_to_display[10].'/end';
}
As explained in the title, I need each order to go into each empty td slot in the above html table. But, if I were to put a .each() function after my .post, all of my tds will turn into the first data gotten from the script, meaning data_arr[1].

First, please have a look at:
http://php.net/manual/en/function.json-encode.php
http://www.islandsmooth.com/2010/04/send-and-receive-json-data-using-ajax-jquery-and-php/
Second: better use div insted tables, this would make you independent of client device screen size.
http://csswizardry.com/2011/08/building-better-grid-systems/
Third, this is absolutly horrible code but it should be your solution:
$("td.load_ads").each(function(){
$(this).html("Place a New Ad Free!");
});
var count=$("td.load_ads").length; //18
$.post('/fetch_orders.php',{count:count},function(data){
var data_arr = [];
var rows=data.split('/end');
for(index=0;index < rows.length;index++){
var row = rows[i].split('/');
for (var x in row) {
data_arr.push(row[x]);
}
}
var i = 0;
$("td.load_ads").each(function () {
if (data_arr[i]) {
$(this).html(data_arr[i]);
}
i++;
});
}

$query = Sql_Query("SELECT * FROM Table");
$num_rows = mysql_num_rows($query);
for($i=0; $i < $num_rows; $i=$i+5)
{
$query1 = Sql_Query("SELECT * FROM Table LIMIT ".$i.", 5 ");
print '<td valign="top">';
while ($row=mysql_fetch_assoc($query1))
{
print '<input type="checkbox" name="chk_group1[]" id="chk_group1" value="'.$row['isp_name'].'" /> '.$row['isp_name'].'<br />';
}
print '</td>';
}

Related

Calculate sum value jQuery PHP

I have a problem calculating the sum of the data from the database and from user input, can Y'all help me?
this is the PHP code
1st value (stok di database) is data from database, and 2nd value (stok fisik) is data from user input, and selisih is 2nd value - 1st value.
<div class="box-content nopadding" style="overflow: auto;">
<table width="400px" class="table table-hover table-nomargin table-bordered">
<thead>
<tr>
<th style="text-align: center; vertical-align:middle;" rowspan="2">No</th>
<th style="text-align: center; vertical-align:middle;" rowspan="2">Nama Barang</th>
<th style="text-align: center; vertical-align:middle;" colspan="2">Stok</th>
<th style="text-align: center; vertical-align:middle;" rowspan="2">Selisih</th>
</tr>
<tr>
<th style="text-align: center; vertical-align:middle;">Stok di Database</th>
<th style="text-align: center; vertical-align:middle;">Stok Fisik</th>
</tr>
</thead>
<tbody>
<?php
$data = $db->query("select id, nama_barang, stock from tbl_atk group by nama_barang");
for ($i = 0; $i < count($data); $i++) {
$no = $i + 1;
if ($no % 2 ==0) $bg ='#FBFBFB';
else $bg = '#FFFFFF';
// $total = 'result' - $data[$i]['stock'];
$tot_masuk = $tot_masuk + "stock_op";
$tot_keluar = $tot_keluar + $data[$i]['stock'];
$grand_tot = $tot_masuk - $tot_keluar;
?>
<tr>
<td style="text-align: center; vertical-align:middle;"><?php echo $no; ?></td>
<td><?php echo $data[$i]['nama_barang']?></td>
<td style="text-align: right;" class="so"><?php echo $data[$i]['stock']; ?></td>
<td><input type="number" class="form-control so" id="stock_op" name="stock_op" style="text-align: left"></td>
<td style="text-align: right; font-weight:bold;"><output class="result"></output></td>
</tr>
<?php
}
?>
<script src="../js/jquery.min.js"></script>
<script>
$(document).on('input','.so',function(){
var totalSum = 0;
var currentRow = $(this).closest('tr');
currentRow.find('.so').each(function(){
var inputVal = ($(this).is('input')) ? $(this).val() : parseInt($(this).html());
console.log(inputVal);
if($.isNumeric(inputVal)){
totalSum += parseFloat(inputVal);
}
});
currentRow.find('.result').val(totalSum);
});
</script>
<tr style="background-color:#eaeaea; font-weight:bold;">
<td style="text-align: center; vertical-align:middle;"></td>
<td style="text-align: right;">Selisih</td>
<td style="text-align: right;"><?php echo $tot_keluar; ?></td>
<td style="text-align: right;"><?php echo $tot_masuk; ?></td>
<td style="text-align: right;"><?php echo $grand_tot; ?></td>
</tr>
</tbody>
</table>
</div>
and this is the User Interface
Change the .so to so in the below input fields.
<td style="text-align: right;" class="form-control .so"><?php echo $data[$i]['stock']; ?></td>
<td><input type="number" class="form-control .so" id="stock_op" name="stock_op" style="text-align: left"></td>
Change id result to class result in below line
<td style="text-align: right; font-weight:bold;"><output id="result"></output></td>
New Update
Give a specific class to your stok fisik cell
<tr style="background-color:#eaeaea; font-weight:bold;">
<td style="text-align: center; vertical-align:middle;"></td>
<td style="text-align: right;">Selisih</td>
<td style="text-align: right;"><?php echo $tot_keluar; ?></td>
<td class="grandResult" style="text-align: right;"><?php echo $tot_masuk; ?></td>
<td style="text-align: right;"><?php echo $grand_tot; ?></td>
</tr>
change your jquery code to this
$(document).on('input','.so',function(){
var grandSum = 0;
var totalSum = 0;
var currentRow = $(this).closest('tr');
currentRow.find('.so').each(function(){
var inputVal = ($(this).is('input')) ? $(this).val() : parseInt($(this).html());
if($.isNumeric(inputVal)){
totalSum += parseFloat(inputVal);
}
});
currentRow.find('.result').val(totalSum);
$('input.so').each(function(){
var cVal = ($(this).is('input')) ? $(this).val() : parseInt($(this).html());
if($.isNumeric(cVal)){
grandSum += parseFloat(cVal);
}
});
$('.grandResult').val(grandSum);
});
Hello Fauzio, I have created a sample table with 3 columns,
1. t_id (ie. id )
2. t_name ( ie name barang)
3. t_value (ie stock di database)
I created a table and displayed the values of each rows in the table. all values from column t_value is added in java script array. then as user enters the value for that particular row.
On click of the button , the value for that particular row is picked from db_column and user column and the result is printed in the result column
<?php
$sql = "SELECT t_id,t_name, t_value FROM test_table";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$main_array = array();
$count=0;
while($row = $result->fetch_assoc()) {?>
<tr>
<td class="no">
<?php echo $count;?>
</td>
<td class="name">
<?php echo $row["t_name"]."<br>";?>
</td>
<td class="db_value">
<?php
array_push($main_array,$row["t_value"]);
echo $row["t_value"]."<br>";?>
</td>
<td class="user_value">
<form method="post">
<input type="number" value="">
<button id="cal" type="button" class="<?php echo $count;?>"> Calculate </button>
</form>
</td>
<td class="result">
<input type="tel" name="" value="" id="result_<?php echo $count;?>">
</td>
</tr>
<?php $count++;}?>
</tbody>
</table>
</div>
<script type="text/javascript">
jQuery(document).ready(function() {
var main_array = new Array();
<?php foreach($main_array as $key => $val){ ?>
main_array.push('<?php echo $val; ?>');
<?php } ?>
jQuery('#cal').on('click', function() {
id = jQuery(this).attr('class');
value_1st = main_array[id];
value_2nd = jQuery(jQuery(this).closest('.user_value')).find('input[type="number"]').val();
result = value_1st + value_2nd;
input_field = jQuery(jQuery(jQuery(this).closest('.user_value')).next()).find('#result_' + id);
input_field.val(result);
});
});
</script>

ajax result not showing properly in table

I need to refresh contents in table every 5 seconds. I did this with ajax and setInterval functions. But the result is not properly displayed.
This is the result displaying. Here the first row is replaced by last row. I couldn't find the reason.
Here is my code.
My controller
public function latestReport() {
$data['incomingCount'] = $this->Home_model->findCount('incoming');
$data['outgoingCount'] = $this->Home_model->findCount('outgoing');
$data['droppedCount'] = $this->Home_model->findCount('drop');
$data['latestReport'] = $this->Home_model->latestReport(10);
print_r(json_encode($data));
}
Script
function latestReport() {
$.ajax({
url : base_url + 'Home/latestReport',
type : 'POST',
success:function(data) {
var res = $.parseJSON(data);
$('#incomingCount').text(res.incomingCount);
$('#outgoingCount').text(res.outgoingCount);
$('#droppedCount').text(res.droppedCount);
var latestCount = res.latestReport.length;
for(var i = 0; i < latestCount; i++){
var count = parseInt(i) + 1;
$('#resNo').text(count);
$('#resSource').text(res.latestReport[i]['Source']);
$('#resDest').text(res.latestReport[i]['Destination']);
$('#resCallerID').text(res.latestReport[i]['CallerID']);
$('#CallerTime').text(res.latestReport[i]['CallStartTime']);
$('#resStatus').text(res.latestReport[i]['Status']);
$('#resAgent').text(res.latestReport[i]['Agent']);
$('#resType').text(res.latestReport[i]['Type']);
}
}
});
}
var myVar = setInterval(latestReport, 5000);
HTML
<table class="normal-table" id="senderidList">
<tr>
<th style="width: 100px">Sl No</th>
<th style="width: 100px">Source</th>
<th>Destination</th>
<th>CallerID</th>
<th style="width: 150px">Call Start Time</th>
<th>Status</th>
<th>Agent</th>
<th>Type</th>
</tr>
<?php if( isset($latestReport) && !empty($latestReport)) {
$i = 1;
foreach($latestReport as $report) {
?>
<tr>
<td id="resNo"><?php echo $i++;?></td>
<td id="resSource"><?php echo $report['Source']?></td>
<td id="resDest"><?php echo $report['Destination']; ?></td>
<td id="resCallerID"><?php echo $report['CallerID']?></td>
<td id="CallerTime"><?php echo date('d-m-Y h:i:s A', strtotime($report['CallStartTime'])); ?></td>
<td id="resStatus"><?php echo $report['Status']?> </td>
<td id="resAgent"><?php echo $report['Agent']?> </td>
<td id="resType"><?php echo $report['Type']?> </td>
</tr>
<?php } }
else {?>
<tr><td colspan="4"> No details available</td></tr>
<?php } ?>
</table>
I am getting the result from controller properly. But something happened when showing in table.
This is because the cells in each row all have the same ID, so you are updating the first row 10 times.
HTML elements should not have duplicate IDs.
You can do this instead, in PHP:
<tr id="row-<?php echo $i; ?>">
<td class="resNo"><?php echo $i++;?></td>
...
Then in JavaScript:
$('#row-' + count + ' .resNo').text(count);
...
Also, there is no need for parseInt(i) - just use i.
You can display your data without giving ID's to 'td' tags in HTML
make your html as follow
<table class="normal-table" id="senderidList">
<thead>
<tr>
<th style="width: 100px">Sl No</th>
<th style="width: 100px">Source</th>
<th>Destination</th>
<th>CallerID</th>
<th style="width: 150px">Call Start Time</th>
<th>Status</th>
<th>Agent</th>
<th>Type</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Write following code in Success of Your ajax function for appending row 1 by 1
$('#senderidList tbody').empty();//clear your data
var TableBody = '';
if (data.d.length > 0) {
//following $.each loop will Concate data one by one
$.each(data.d, function (i, latestReport) {
TableBody += '<tr><td>' + i + 1 + '<td><td>' + latestReport['Source'] + '<td><td>' + latestReport['Destination'] + '<td><td>' + latestReport['CallerID'] + '<td><td>' + latestReport['CallStartTime'] + '<td><td>' + latestReport['Status'] + '<td><td>' + latestReport['Agent'] + '<td><td>' + latestReport['Type'] + '<td></tr>';
});
}
else
{
TableBody = '<tr><td colspan="4"> No details available</td></tr>';
}
//append the created html to the table body using append function
$('#senderidList tbody').append(TableBody);
if You want to give Id to every 'td' then you can give in $.each
<td id="yourID'+i+'"> for every td in body tag

jquery function not working on multiple rows

I have a table generated by jQuery, and a function that triggers an event when pressing ENTER.
The table generates correctly, but the function only works in the first wor of the table.
My html for the table is as follows:
<table border="1" id="PlantillaTable" name="PlantillaTable">
<tbody>
<tr>
<th rowspan="2" scope="col">Cargo</th>
<th colspan="12" scope="col">Escenario de Registro</th>
</tr>
<tr>
<td colspan="2">Folio</td>
<td colspan="2">Propietario</td>
<td >Grupo</td>
<td >Edad</td>
<td colspan="2">Folio</td>
<td colspan="2">Suplente</td>
<td >Grupo</td>
<td >Edad</td>
</tr>
<tr id="FilaTable">
<th scope="row" col="1" row="1">Cargo</th>
<td col="2" row="1">LISTA</td>
<td col="3" row="1">
<input type="text" id="AspiranteField" name="AspiranteField" placeholder="FOLIO" />
</td>
<td col="4" row="1">FOTO</td>
<td col="5" row="1">NOMBRE</td>
<td col="6" row="1">GRUPO</td>
<td col="7" row="1">EDAD</td>
<td col="8" row="1">LISTA</td>
<td col="9" row="1">
<input type="text" id="AspiranteField" name="AspiranteField" placeholder="FOLIO" />
</td>
<td col="10" row="1">FOTO</td>
<td col="11" row="1">NOMBRE</td>
<td col="12" row="1">GRUPO</td>
<td col="13" row="1">EDAD</td>
</tr>
</tbody>
And my function is as follows:
$.fn.pressEnter = function(fn) {
return this.each(function() {
$(this).bind('enterPress', fn);
$(this).keyup(function(e){
if(e.keyCode == 13)
{
$(this).trigger("enterPress");
}
})
});
};
$('input').pressEnter(function(){
var trid = ($(this).closest('tr').attr('id'));
var opcion = ($(this).closest('td').index());
var valor = $(this).val();
$.getJSON("php/getAspiranteNombre.php?AspiranteId="+valor,function(data){
$.each(data,function(index,item) {
if(opcion < 4)
{
$("#"+trid+" td").eq(3).html('<p>'+item.NAME+'</p>');
$("#"+trid+" td").eq(4).html('<p>'+item.GRUPO+'</p>');
$.getJSON("php/getFoto.php?AspiranteId="+valor,function(data2){
$("#"+trid+" td").eq(2).html('<img src="aspiranteFoto/thumb_'+data2+'" width="50px" height="50px"/>');
});
$.getJSON("php/getEdad.php?Nacimiento="+item.EDAD,function(data3){
$("#"+trid+" td").eq(5).html('<p>'+data3+'</p>');
});
}
else
{
$("#"+trid+" td").eq(9).html('<p>'+item.NAME+'</p>');
$("#"+trid+" td").eq(10).html('<p>'+item.GRUPO+'</p>');
$.getJSON("php/getFoto.php?AspiranteId="+valor,function(data2){
$("#"+trid+" td").eq(8).html('<img src="aspiranteFoto/thumb_'+data2+'" width="50px" height="50px"/>');
});
$.getJSON("php/getEdad.php?Nacimiento="+item.EDAD,function(data3){
$("#"+trid+" td").eq(11).html('<p>'+data3+'</p>');
});
}
});
});
})
Which basically asks for a value in a database and places it in the spaces. The problem is that, in the first row of the table (dynamically generated) the function works perfectly, but in the subsequent rows it doesn't do anything.
Thanks in advance for your help!
You have to change the way to this one:
$("#PlantillaTable").find("input").keyup(function(ev) {
if (ev.which === 13 ) {
//yout code here...
}
});
Attaches to all input values inside this table the enter button handler.
http://jsfiddle.net/csdtesting/jkfL2v5s/
You first have to loop through each tr separately, then you can target the td's inside.
You can loop through the rows using $.each() like this:
$("table tr").each(function(i,v){
$(this).find("td:eq(3)").html('<p>'+item.NAME+'</p>');
....
});
and it will go through all your rows, not just the first one.

Get data inside html tags using Simple HTML DOM Parser:

I want to get all the information inside the html tags and display them in a table. I'm using Simple HTML DOM Parser. I tried the following code but I'm only getting the LAST COLUMN (Column:Total). How do I get the data from the other columns?
foreach($html->find('tr[class="tblRowShade"]') as $div) {
$key = '';
$val = '';
foreach($div->find('*') as $node) {
if ($node->tag=='td'){
$key = $node->plaintext;
}
}
$ret[$key] = $val;
}
Here's my code for the table
<tr class="tblRowShade">
<td width="12%"><strong>Project</strong></td>
<td width="38%"> </td>
<td width="25%"><strong>Recipient</strong></td>
<td width="14%"><strong>Municipality/City</strong></td>
<td width="11%" nowrap="nowrap" class="td_right"><strong>Implementing Unit</strong></td>
<td width="11%" nowrap="nowrap" class="td_right"><strong>Release Date</strong></td>
<td align="right" width="11%" class="td_right"><strong>Total</strong></td>
</tr>
<tr class="tblRowShade">
<td colspan="2" >Livelihood Programs</td>
<td >Basic Espresso and Latte</td>
<td nowrap="nowrap"></td>
<td >DOLE - TESDA Regional Office IV-A</td>
<td nowrap="nowrap">2013-06-11</td>
<td align="right" nowrap="nowrap" class="td_right">1,500,000</td>
</tr>
Why do you have $div->find('*')? you can try $div->find('td') instead. This should produce correct result. Otherwise you can also try to iterate over children: foreach($div->children as $node)
Assuming you are trying to use the first row as $key and the rest for the data, you might want to alter your HTML code by simply add th in the first row, which is your header: <tr><th>…</th></tr>. This way you can get the keys by $div->find('th'). I suppose using the first row is okay as well.
As alamin.ahmed said, it would be better to search for td instead...
Here's a working example :
$text = ' <tr class="tblRowShade">
<td width="12%"><strong>Project</strong></td>
<td width="38%"> </td>
<td width="25%"><strong>Recipient</strong></td>
<td width="14%"><strong>Municipality/City</strong></td>
<td width="11%" nowrap="nowrap" class="td_right"><strong>Implementing Unit</strong></td>
<td width="11%" nowrap="nowrap" class="td_right"><strong>Release Date</strong></td>
<td align="right" width="11%" class="td_right"><strong>Total</strong></td>
</tr>
<tr class="tblRowShade">
<td colspan="2" >Livelihood Programs</td>
<td >Basic Espresso and Latte</td>
<td nowrap="nowrap"></td>
<td >DOLE - TESDA Regional Office IV-A</td>
<td nowrap="nowrap">2013-06-11</td>
<td align="right" nowrap="nowrap" class="td_right">1,500,000</td>
</tr>';
echo "<div>Original Text: <xmp>$text</xmp></div>";
//Create a DOM object
$html = new simple_html_dom();
// Load HTML from a string
$html->load($text);
// Find all elements
$rows = $html->find('tr[class="tblRowShade"]');
// Find succeeded
if ($rows) {
echo count($rows) . " \$rows found !<br />";
foreach ($rows as $key => $row) {
echo "<hr />";
$columns = $row->find('td');
// Find succeeded
if ($rows) {
echo count($columns) . " \$columns found in \$rows[$key]!<br />";
foreach ($columns as $col) {
echo $col->plaintext . " | ";
}
}
else
echo " /!\ Find() \$columns failed /!\ ";
}
}
else
echo " /!\ Find() \$rows failed /!\ ";
here's the output of the above code:
You must be aware that the two rows doesnt contain the same number of columns... then you must handle that in your program.

jQuery with php while on table tr td sum of the column for sub total

i was wondering if my jquery is correct for add the td and get the total for the sub total and total.
my jquery is,
$(document).ready(function(){
var sum = 0;
var td = $('input[name=sumof]').val();
jQuery.each(td,function(number){
sum += parseInt($(this).val());
$('#total_f').val(sum);
});
})
and this is my html
<div class="quotation_computation" style="margin-top:50px;">
<table cellpadding="5" cellspacing="0" width="100%">
<tr>
<th>#</th>
<th>Definition</th>
<th>Amount</th>
<th>Total</th>
<th>BTW</th>
</tr>
<?
$get_details = mysql_query( "SELECT * FROM jon_com_quo_computation WHERE com_code = '".$_GET['ccom']."' " ) or die ( mysql_error());
$found_record = mysql_num_rows( $get_details );
if ( $found_record != 0 ) {
while( $set_det = mysql_fetch_array( $get_details ) ) {
$total = $set_det['quo_quantity'] * $set_det['quo_amt'];
?>
<tr>
<td class="add_text">
<?=$set_det['quo_quantity'];?> x
</td>
<td class="add_text" width="250"><?=$set_det['quo_definition'];?></td>
<td class="sum_text">
<?=$set_det['quo_amt'];?>
<input type="hidden" name="sumof" value="<?=$set_det['quo_amt'];?>" />
</td>
<td class="add_text" id="total"><?=$total;?></td>
<td class="add_text"><?=$set_det['quo_btw'];?></td>
</tr>
<?
}
} else {
?>
<tr>
<td class="add_text">#</td>
<td class="add_text">Definition</td>
<td class="add_text">Amount</td>
<td class="add_text" id="total">Total</td>
<td class="add_text">BTW</td>
</tr>
<?
}
?>
</table>
</div>
<div class="sub_total_computation" style="width:200px; position:relative; left:325px;">
<?
$get_total_computation = SET_SQL( "SELECT quo_btw FROM jon_com_quo_computation WHERE com_code = '".$_GET['ccom']."' " );
?>
<table cellpadding="5" cellspacing="0" width="100%">
<tr>
<td><strong>Sub Total</strong></td>
<td>
<span id="total_f"></span>
<input type="hidden" name="total_f" value="" />
</td>
</tr>
<tr>
<td><?=$get_total_computation['quo_btw'];?></td>
<td><?=$btw;?></td>
</tr>
<tr>
<td><strong>Total</strong></td>
<td><?=$btw;?></td>
</tr>
</table>
</div>
if you saw the hidden name=sumof im going to put there the answer also in the td class=sum_text but the answer did not appear.
Do we need to use on .keyup function so that the jquery will appear?
Or i just need to use the PHP so that it will work?
thank you sir.
Try this:
$(document).ready(function(){
var sum = 0;
$('input[name=sumof]').each(function(){
sum += parseInt($(this).val());
});
$('#total_f').val(sum);
});
Your variable td would only get one value out of the input elements, and NOT be sufficient to use as an object (the input element) to loop with your each() function. Also you only need to have the function output the sum once, so I took it out of the each loop.
To further make the function efficient You could use just the contents of the td element instead and completely remove the hidden input element:
$(document).ready(function(){
var sum = 0;
$('td.sum_text').each(function(){
sum += parseInt($(this).text());
});
$('#total_f').val(sum);
});
You have a problem here:
var td = $('input[name=sumof]').val(); // you are getting the value of the first matched element
jQuery.each(td,function(number){
sum += parseInt($(this).val());
You are assuming that td contains a collection, but when you use val(), the result is Description: Get the current value of the first element in the set of matched elements.
So just change it to:
var td = $('input[name=sumof]');

Categories