I've been searching on how to achieve this. I got a lot of info from this site, but all couldn't help.
I'm trying to populate a table with the data I got from PHP File Using Ajax
I've been able to get the data, at least into the console. But when i try sending it to the the table, nothing is shown. No errors shown, Just blank.
console.log(newarr)
brings
gives this answer (image)
But when I do this $("#report").html(newarr);, nothing happens.
Here is the code:
ajax
$.post('./process/assetReport.php', data, function(data) {
genData = JSON.parse(data);
var newarr;
for (var key in genData) {
if (data.hasOwnProperty(key)) {
newarr = genData[key];
//console.log(newarr);
$("#report").html(newarr);
}
}
});
php
foreach($all as $item) {
$assetid = $item['assetid'];
$staffid = $item['staffid'];
$row2 = $user->showone('assets', 'assetid', $assetid);
$row3 = $user->showone('staff', 'staffid', $staffid);
$useData[] = array(
'asset' => $row2['name'],
'staff' => $row3['name'],
'cost' => $item['cost']
);
}
echo json_encode($useData);
The table I need to populate
<table class="table" id="reportTable">
<thead>
<tr>
<th>Asset Name</th>
<th>Assigned To</th>
<th>Cost</th>
</tr>
</thead>
<tbody id="report">
</tbody>
<tfoot>
<tr>
<td><button type="button" class="btn btn-success" id="printReport"><i class="glyphicon glyphicon-print"></i> Print</button></td>
</tr>
</tfoot>
</table>
I hope my question is explanatory enough
Thank you
I have created a stub of a JSON array, and shown how to loop through it appending rows to your table as you go. I excluded your key check, as I wasn't sure the relevance. A variation of this code should reside in the callback to your $.post()
data = [{
asset: "steve",
staff: "steve",
cost: '$999,999.99'
}, {
asset: 'bob',
staff:"bob",
cost: '$0.99'
}];
var $row = $("<tr><td></td><td></td><td></td></tr>"); //the row template
var $tr;
$.each(data, function(i, item) {
$tr = $row.clone(); //create a blank row
$tr.find("td:nth-child(1)").text(item.asset); //fill the row
$tr.find("td:nth-child(2)").text(item.staff);
$tr.find("td:nth-child(3)").text(item.cost);
$("#report").append($tr); //append the row
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>Asset Name</th>
<th>Assigned To</th>
<th>Cost</th>
</tr>
</thead>
<tbody id='report'>
<tbody>
</table>
I think you need to user genData[0] instead of genData as your are using $useData[] inside php or user $useData instead of $useData[]
So the code should be look like followings:
$.post( './process/assetReport.php', data, function (data) {
genData = JSON.parse(data);
var newarr;
for(var key in genData[0]) {
if(data.hasOwnProperty(key)){
newarr = genData[key];
//console.log(newarr);
$("#report").html(newarr);
}
}
});
And the php:
foreach ($all as $item) {
$assetid = $item['assetid'];
$staffid = $item['staffid'];
$row2 = $user->showone('assets', 'assetid', $assetid);
$row3 = $user->showone('staff', 'staffid', $staffid);
$useData[] = array(
'asset' => $row2['name'],
'staff' => $row3['name'],
'cost' => $item['cost']
);
}
echo json_encode($useData);
Related
I have some issues in getting values from datatable that i imported from excel.
i Want to pass the rows that selected (at least can be viewed in alert), here's the case.
the value that i want is like
Name : A. Mused , No HP : 087....
Name : Aida Bugg, No HP : 089....
Name : Allie Grater, No HP : 087...
but the result is just like this screenshot :
result popup alert and data
here's the code :
html
#if (Model != null)
{
<table id="tablePenerima" class="table table-striped table-bordered animate__animated animate__fadeInRight" cellpadding="0" cellspacing="0">
<thead>
<tr>
#foreach (DataColumn col in Model.Tables[0].Columns)
{
<th align="center">#col.ColumnName</th>
}
</tr>
</thead>
<tbody>
#foreach (DataRow row in Model.Tables[0].Rows)
{
<tr >
#foreach (DataColumn col in Model.Tables[0].Columns)
{
<td align="center">#row[col.ColumnName]</td>
}
</tr>
}
</tbody>
</table>
}
and the javascript :
$(document).ready(function () {
var table = $('#tablePenerima').DataTable({
dom: 'Bfrtip',
buttons: [
'selectAll',
'selectNone',
],
select: true
});
$('#tablePenerima tbody').on('click', 'tr', function () {
$(this).toggleClass('selected');
});
$('#btnBlast').click(function () {
var ids = $.map(table.rows('.selected').data(), function (item) {
return item[0]
});
var data = $('#tablePenerima').DataTable().row('.selected').ids();
console.log(ids);
alert("Name:" + ids[0] + "\nNo HP:" + ids[2]);
});
});
I hope all of you can solve my problem because my knowledge in js is still weak. Thanks :)
I have no experience with DataTable package, but i think the problem is your map function. It returns the first row of selected rows.
var ids = $.map(table.rows('.selected').data(), function (item) {
return item[0]
});
Instead of
return item[0]
You should return all selected rows;
return item
In $('#btnBlast').click event
I'm making a web-based POS. I have two table, one is for displaying the search products using jquery and when I clicked the product it will transfer to the second table. So my second table is dynamically dependent of what the user clicked. This is my table look like with css.
I want to get the total price of Sub.Total column automatically and display to the bottom specially in the Total p tag.
This is my html table code.
<table id="table2">
<thead>
<tr>
<th>Barcode</th>
<th>Description</th>
<th>Price</th>
<th>Unit</th>
<th>Qty</th>
<th>Sub.Total</th>
<th>Action</th>
</tr>
</thead>
<tbody id="tableData">
</tbody>
</table>
<table id="table1">
<thead>
<tr>
<td>Barcode</td>
<td>Product Name</td>
<td>Price</td>
<td>Unit</td>
<td>Stocks</td>
</tr>
</thead>
<tbody id="products">
</tbody>
</table>
This is my query from search box.
$show = "SELECT * FROM products WHERE product_name LIKE '$name%' ";
$query = mysqli_query($db,$show);
if(mysqli_num_rows($query)>0){
while($row = mysqli_fetch_array($query)){
echo "<tr class='js-add' data-barcode=".$row['id']." data-product=".$row['product_name']." data-price=".$row['sell_price']." data-unt=".$row['unit']."><td>".$row['id']."</td><td>".$row['product_name']."</td>";
echo "<td>₱".$row['sell_price']."</td>";
echo "<td>".$row['unit']."</td>";
echo "<td>".$row['quantity']."</td>";
}
}
This is for displaying the cliked rows from searched products.
$('body').on('click','.js-add',function(){
var target = $(this);
var product = target.attr('data-product');
var price = target.attr('data-price');
var barcode = target.attr('data-barcode');
var unit = target.attr('data-unt');
swal("Enter number of item to buy:", {
content: "input",
})
.then((value) => {
if (value == "") {
swal("Error","Entered none!","error");
}else{
var qtynum = parseInt(value);
if (isNaN(qtynum)){
swal("Error","Please input a valid number!","error");
}else{
var total = value * price;
$('#tableData').append("<tr><td>"+barcode+"</td
<td>"+product+"</td>
<td>"+accounting.formatMoney(price,{symbol:"₱",format: "%s %v"})+"</td><td>"+unit+"</td>
<td>"+value+"</td>
<td class='totalPrice'>"+accounting.formatMoney(total,{symbol:"₱",format: "%s %v"})+"</td>
<td><button class='btn btn-danger' type='button' id='delete-row'>×</button><tr>");
}
}
});
});
I'd tried this code but it return NaN.
$(document).ready(function(){
var TotalValue = 0;
$("#tableData tr").each(function(){
TotalValue += parseFloat($(this).find('.totalPrice').text().replace(/,/g, "₱"));
});
alert(TotalValue);
});
I'd tried modifying the code but I cant get the job done. Hope someone will help about this one. Thanks in advance.
Edit: Updated answer.
Based off what you tried here would be a working solution using your logic.
$(document).ready(function(){
var TotalValue = 0;
var TotalPriceArr = $('.totalPrice').get()
$(TotalPriceArr).each(function(){
TotalValue +=parseInt($(this).text().replace('₱', ''))
});
alert(TotalValue);
});
Active learner here, trying to figure out how to create a JSON object out of HTML table. I only want the value of one specific TD and want to give each value an incrementing number as a key. I'd like an output like below. My table has a TD for the city names, but it does not have one with a incrementing numerical value so I'd need to add that another way.
{
"mycities" : [
{
"Seattle" : "1",
"Chicago" : "2",
"New York" : "3"
"Pitt" : "4",
"LA" : "5",
"Fresno" : "6"
},
]
}
Here is what my table looks like:
<table>
<thead>
<tr>
<th>city name</th>
<th>other city info</th>
</tr>
</thead>
<tbody>
<tr>
<td>Seattle</td>
<td>Lots of rain</td>
</tr>
etc,etc,etc
</tbody>
</table>
I've tried using a replacer function but haven't got it figured out after much googling. Any help is appreciated!
$(document).ready(function(){
$("body").on("click",".submitButtonPri",function(){
count= 1;
function replacer(key, value) {
if (typeof value === 'string') {
return count;
}
return value;
}
var myRows = [];
var $headers = $(".rightDash > table thead th");
var $rows = $(".rightDash > table tbody tr").each(function(index) {
$cells = $(this).find("td.titlePri");
myRows[index] = {};
$cells.each(function(cellIndex) {
myRows[index][$($cells[cellIndex]).text()] = $(this).text();
});
count++;
});
var myObj = {};
myObj.myrows = myRows;
console.log(JSON.stringify(myObj,replacer));
});
});
Use reduce to iterate over the trs in the body, using the text content of the first td in the tr as the city name. The third argument to the function provided to reduce represents the iteration index:
const cityData = [...document.querySelectorAll('tbody > tr')]
.reduce((a, tr, i) => {
a[tr.children[0].textContent] = i + 1;
return a;
}, {});
console.log(
{ mycities: [
cityData
]}
);
<table>
<thead>
<tr>
<th>city name</th>
<th>other city info</th>
</tr>
</thead>
<tbody>
<tr>
<td>Seattle</td>
<td>Lots of rain</td>
</tr>
<tr>
<td>Chicago</td>
<td>Lots of rain</td>
</tr>
<tr>
<td>New York</td>
<td>Lots of rain</td>
</tr>
</tbody>
</table>
You can start with this simple script:
$('td').each(function(index, obj) {console.log(index, $(this).html())});
It returns all what you need and you just need assemble JSON by any way
$(function() {
var companyId = 1740963;
JA.get('api/' + companyId + '/Transaction', function(data) {
if (!data)
return;
var items = data.Items;
if (!items)
return;
for (var i = 0; i < items.length; i++) {
var expense = items[i];
JA.renderTemplateFromPath('expenseListRow', items[i], function(template) {
var $template = $(template);
$('#expenseListBody').append($template);
$template.find('.expenseDate p').html(function(index, value) {
return moment(value, "YYYY-MM-DDTHH:mm:ss").format("DD/MM/YYYY");
});
})
}
});
})
<table id="expenseList">
<tr id="expenseListHead">
<th id="numberID">Number</th>
<th>Date</th>
<th>Name</th>
<th>Description</th>
<th>Reference</th>
<th class="alignRight">Amount</th>
<th class="alignRight"></th>
</tr>
<tbody id="expenseListBody">
<tr class="expenseListRow">
<td></td>
<td class="expenseDate"></td>
<td></td>
<td></td>
<td></td>
<td class="alignRight"></td>
<td class="alignRight"></td>
</tr>
</tbody>
</table>
As you can see in the image, there are multiple numbers in random order being pulled from an API, the list carry's on for a while.
What I am wondering is if anyone could help me work out how to sort these numbers in ascending order (starting from 1) and so on, instead of it adding them randomly, like I said this data is being pulled from an API that has been written so I'm struggling to work out how to do this. If anymore info is needed to help answer let me know. Thanks in advance.
If your list contains only numbers you can use the sort function available with Array. just call
var sortedList = yourList.sort();
If its an array of objects and the numbers are inside as a field then you can override the sort function as mentioned here
I've a bit of experience coding in php but am fairly new to js. What I'm trying to do in js is create a simple order form, each line is to have a text box indicating the quantity to be ordered, product name and product price, with the latter to be populated from product array prod. My fairly rudimentary first attempt appears below, which needless to say doesn't work.
<body onload="populate()">
<table id="demo">
<thead>
<tr>
<th>Quantity</th>
<th>Product</th>
<th>Price</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script>
function populate(){
var prod; //array of objects with name and price attributes
var table = document.getElementById("theTable");
for (var i=0; i<prod.length; i++)
{
var newTr = table.insertRow(-1);
var numOrdered=document.createElement('input');
numOrdered.type='text';
numOrdered.id= "product "+i; //assigning id of "product i" to each product i
newTr.insertCell(0).appendChild(num);
newTr.insertCell(-1).appendChild(document.createTextNode(prod["name"]));
newTr.insertCell(-1).appendChild(document.createTextNode(prod["price"]));
}
}
</script>
</body>
Any and all help appreciated.
have a look at the snippet at the bottom.
what's changed is:
in this line you targeted the wrong id, should have been 'demo'
var table = document.getElementById("theTable");
you also needed to reference the correct value in your array inside the loop:
document.createTextNode(prod["name"]);
to:
document.createTextNode(prod[i]["name"]);
and lastly this line:
newTr.insertCell(0).appendChild(num);
to:
newTr.insertCell(0).appendChild(numOrdered);
hope this helps.
function populate() {
var prod = [{
name: 'box',
price: 20
}, {
name: 'plane',
price: 40
}]; //array of objects with name and price attributes
var table = document.getElementById("theTable");
for (var i = 0; i < prod.length; i++) {
var newTr = table.insertRow(-1);
var numOrdered = document.createElement('input');
numOrdered.type = 'text';
numOrdered.id = "product " + i; //assigning id of "product i" to each product i
newTr.insertCell(0).appendChild(numOrdered);
newTr.insertCell(-1).appendChild(document.createTextNode(prod[i]["name"]));
newTr.insertCell(-1).appendChild(document.createTextNode(prod[i]["price"]));
}
}
populate();
<table id="theTable">
<thead>
<tr>
<th>Quantity</th>
<th>Product</th>
<th>Price</th>
</tr>
</thead>
<tbody></tbody>
</table>
Try This code:
I am using jQuery, to create, append and iterating the array(each Loop).It is a better and effective way. Please use jQuery for DOM manipulation.
HTML:
<table id="demo">
<thead>
<tr>
<th>Quantity</th>
<th>Product</th>
<th>Price</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
CSS:
table,td{display:block}
th{width:100px}
td{margin:10px}
JS:
var prod=[{product:'samsung',price:100},{product:'apple',price:200},{product:'micromax',price:300}];
(function($){
$.each(prod,function(index,value){
$('#demo th:eq(0)').append("<td><input type='text'></td>");
$('#demo th:eq(1)').append("<td>"+value.product.toUpperCase()+"</td>");
$('#demo th:eq(2)').append("<td>"+value.price+"</td>")
});
})(jQuery);
Here is the JSFiddle Link:
https://jsfiddle.net/Dee0565/8vww1pwf/