Passing table data with post variables - php

Basically I have a table with a bunch of numbers coming from a database with columns for totals/subtotals. I do not intend to add any of the totals to the database, but I need to pass the total numbers from one page to the next. I can't seem to properly pass them as post variables using PHP... I'm wondering if this is a bad tactic firstly, secondly what should I do instead?
And if this is possible, how would I go about doing it? I haven't been able to derive the text between the < td >'s from using $_POST['tdname'].
Example code:
<form method="POST" action="newcivilreport2.php">
<div style="width:800px;text-align:left;margin:0 auto;padding-bottom:5px;">A. PENDING BALANCE</div>
<table border="1" style="width:800px;" ID="tableA">
<th style="width:40%;"></th>
<th style="width:15%;">Civil</th>
<th style="width:15%;">Asbestos</th>
<th style="width:15%;">Domestic</th>
<th style="width:15%;">Total</th>
<tr>
<td>1. Pending Balance from Previous Month</td>
<td id="PendingCivil" name="PendingCivil">66</td>
<td id="PendingAsbestos">0</td>
<td id="PendingDomestic">0</td>
<td id="PendingTotal">0</td>
</tr>
</table>
<input type="submit" value="Save and Continue -->"></form></div>
newcivilreport2.php:
<?php
$_POST['PendingCivil'];
?>

POST will only send inputs like <input type='text|file|hidden|ect' />. Perhaps you would like to use AJAX. For example:
<table id="tData">
<tbody>
<tr>
<td class='dataVal1'>100</td>
...
$(document).ready(function() {
var toServer = {};
var data = $('#tData tbody tr td').each(function(key, value) {
toServer[$(this).attr('id')] = $(this).text();
});
$.ajax({
url: 'page.php',
data: toServer,
type: 'POST'
})
});

The <td> tag of a table does not provide values for a form.
Use a hidden field for your post:
http://www.w3schools.com/tags/att_input_type.asp
...
<td>1. Pending Balance from Previous Month</td>
<td id="PendingCivil">66<input type="hidden" name="PendingCivil" value="66"></td>
...
Also, is it inside of a form?

Related

Form action not working with table inside form

I have a table inside a form like this:
<form action="file.php" id="myform" method="POST">
<div class="table-responsive ">
<table class="table table-hover" id="tblDetalle">
<thead class="thead-dark">
<tr>
<th>Id</th>
<th>Name</th>
<th>Quant.</th>
<th>Price</th>
<th>Total Price</th>
</tr>
</thead>
<tbody">
<?php
if(!isset($_SESSION['products'])){
}else{
foreach($_SESSION['products'] as $product=>$details){
echo '
<tr class="txtMult">
<th scope = "row">'.$details["code_product"].'</th>
<th scope = "row">'.$details["name_product"].'</th>
<td><input class="val2" type="number" id="quantity" name="quantity" min="1" max="100"></td>
<td class="val1">'.$details["price"].'</td>
<td><span class="multTotal">0.00</span></td>
</tr>
';
};
}
?>
</tbody>
<tfoot>
<tr class="font-weight-bold">
<td colspan=4>Total <span id="grandTotal">0.00</span></td>
<td></td>
</tr>
</tfoot>
</table>
<input type="submit" value="Submit"/>
</div>
</form>
My actual problem is that submit botton isn't working, no actions are taken when I click button.
My idea is send all content of table to file.php through POST method.
There's a script that updates last with price*quantity but I don't think that problem lives there.
<script type="text/javascript">
$(document).ready(function () {
$(".txtMult input").keyup(multInputs);
function multInputs() {
var mult = 0;
// for each row:
$("tr.txtMult").each(function () {
// get the values from this row:
var $val1 = parseInt($('.val1', this).text())
var $val2 = $('.val2', this).val();
var $total = ($val1 * 1) * ($val2 * 1)
$('.multTotal',this).text($total);
mult += $total;
});
$("#grandTotal").text(mult);
}
});
</script>
Anybody can help? :)
Once the small typo in the HTML is corrected and without your PHP logic ( no way to test that - hence hardcoded dummy data ) what you could do would be to use Javascript to send the form data rather than rely upon a regular form submission as was failing for you here. HTML content and text will not be sent via the form - only content from input elements so your form would submit a single field called quantity which is not what you want.
The following uses fetch to send the formData to your intended PHP script.
$(document).ready(function () {
function multInputs() {
var mult = 0;
$("tr.txtMult").each(function () {
var $val1 = parseInt($('.val1', this).text())
var $val2 = $('.val2', this).val();
var $total = ($val1 * 1) * ($val2 * 1)
$('.multTotal',this).text($total);
mult += $total;
});
$("#grandTotal").text(mult);
return mult;
}
const submithandler=(e)=>{
// stop the regular `submit`
e.preventDefault();
// add form data to these variables
let fd=new FormData();
let payload=[];
// process the contents of the HTML table to populate the formData object
$("tr.txtMult").each(function(){
let item={
code:this.firstElementChild.textContent,
name:this.firstElementChild.nextElementSibling.textContent,
value:$('.val2', this).val()
};
// convert object to string
payload.push( JSON.stringify(item) );
});
fd.set('payload', payload );
// send the request
fetch( document.getElementById('myform').action,{ method:'post', body:fd })
.then( r=>r.text() )
.then( text=>{
alert( text )// do stuff with results?
})
.catch( err=>console.log('Error:%o',err) )
};
$(".txtMult input").keyup(multInputs);
$('[type="submit"]').click(submithandler);
});
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="file.php" id="myform" method="POST">
<div class="table-responsive ">
<table class="table table-hover" id="tblDetalle">
<thead class="thead-dark">
<tr>
<th>Id</th>
<th>Name</th>
<th>Quant.</th>
<th>Price</th>
<th>Total Price</th>
</tr>
</thead>
<tbody>
<!-- Hardcoded example data -->
<tr class="txtMult">
<th scope = "row">Code ABC-1</th>
<th scope = "row">Name - 1</th>
<td><input class="val2" type="number" name="quantity" min="1" max="100"></td>
<td class="val1">100</td>
<td><span class="multTotal">0.00</span></td>
</tr>
<tr class="txtMult">
<th scope = "row">Code ABC-2</th>
<th scope = "row">Name - 2</th>
<td><input class="val2" type="number" name="quantity" min="1" max="100"></td>
<td class="val1">200</td>
<td><span class="multTotal">0.00</span></td>
</tr>
<tr class="txtMult">
<th scope = "row">Code ABC-3</th>
<th scope = "row">Name - 3</th>
<td><input class="val2" type="number" name="quantity" min="1" max="100"></td>
<td class="val1">300</td>
<td><span class="multTotal">0.00</span></td>
</tr>
</tbody>
<tfoot>
<tr class="font-weight-bold">
<td colspan=4>Total <span id="grandTotal">0.00</span></td>
<td></td>
</tr>
</tfoot>
</table>
<input type="submit" />
</div>
</form>
It is possible to use tables inside forms but I think you're approach is wrong. you can put a table inside a form or vice versa, and it is often useful to do so. But you need to understand what you are doing.
Tables and forms can be nested either way. But if you put forms into tables, each form must be completely included into a single table cell (one TD element in practice). Thereby the forms are each completely independent.
So try putting the form inside the table cell which requires the input

Bootstrap table not recognizing rows generated using AJAX

For reference :
I'm working with Bootstrap-table using Bootstrap v3.3.6
I'm trying to populate my table using AJAX and jQuery, but the problem is that when i do so none of bootstrap extensions seems to work with those rows.
I'm working on a data table using some extensions as the following :
`<table id="table" data-toggle="table" data-pagination="true" data-search="true" data-show-columns="true" data-show-pagination-switch="true" data-show-refresh="true" data-key-events="true" data-show-toggle="true" data-resizable="true" data-cookie="true" data-cookie-id-table="saveId" data-show-export="true" data-click-to-select="true" data-toolbar="#toolbar">
<thead>
<tr>
<th data-field="state" data-checkbox="true"></th>
<th>ID</th>
<th>ISBN</th>
<th>Description</th>
</tr>
</thead>
<tbody id="books-data">
<!-- table data rows to be inserted here -->
</tbody>
`
If i'm filling the table using PHP everything seems to be working fine, by 'everything' i mean displaying data as well as the automatically added attributes to table rows as adding a chekbox in the first <td> and data-index attribute for every column in every row.
However, filling the table using AJAX only fills the table with data and there is no interaction between the table and its rows, no bootstrap-table attributes or checkboxes are added as well as no extensions seems to be working with those rows (for example export, rows selection ...)
For more detail :
When embedding PHP code into table columns:
source code :
while ($row = mysqli_fetch_array($result)){ ?>
<tr>
<td></td>
<td><?php echo $row['id'] ?></td>
<td><?php echo $row['isbn']; ?></td>
<td><?php echo $row['description']; ?></td>
</tr>
<?php } ?>
Generated code by bootstrap-table:
<tr data-index="0">
<td class="bs-checkbox ">
<input data-index="0" name="btSelectItem" type="checkbox">
</td>
<td style>
<!-- data -->
</td>
<td style> <!-- the same thing... --> </td>
</tr>
When generating rows dynamically using AJAX :
<tr>
<td></td>
<td><!-- data --></td>
<td><!-- data --></td>
<td><!-- data --></td>
</tr>
jQuery function used :
$(function()
{
$.ajax({
url:"fetch_books.php",
method:"POST",
dataType:"json",
success:function(data)
{
for(let count=0; count<data.length; count++)
{
let html_data = '<tr><td></td>';
html_data += '<td>'+data[count].id_livre+'</td>';
$('#books-data').append(html_data);
}
}
})
});
I want the result to be the same as when i embed php inside each column in my table, i don't even know why i'm having this issue, i need some help.
Have you tried using their method for loading JSON instead of your own jQuery?
From: https://bootstrap-table-docs3.wenzhixin.net.cn/getting-started/#usage-via-javascript
"We can also use remote URL data by setting url: 'data1.json'.
$('#table').bootstrapTable({
url: 'data1.json',
columns: [{
field: 'id',
title: 'Item ID'
}, {
field: 'name',
title: 'Item Name'
}, {
field: 'price',
title: 'Item Price'
}, ]
});
<table id="table"></table>
If you don't want to use their supplied method then maybe try adding the classes and data-index etc. that you see in the bootstrapped table to the table you're generating...
let html_data = '<tr><td></td>';
=>
let html_data = '<tr data-index="0"><td class="bs-checkbox "><input data-index="0" name="btSelectItem" type="checkbox"></td>';
though I don't think that will get you working... it should at least style things correctly. You'll need to use a way that gets everything pulled into the DOM correctly. I'd try using Bootstrap-table's method for loading JSON they have supplied above. You might have to create a PHP script that takes some arguments and returns properly formatted JSON for their method to work.

How to get submit button in different table rows to perform different SQL queries?

So I'm having a problem that I've been trying to work on for quite a while now but I don't really know how to do it.
I have multiple submit buttons in a table (one per row). How do I get each submit button to perform a different SQL task? To explain further...
So I have a table that looks something like this (This is the HTML code from View Source, without the underlying PHP code that generates the table contents):
<table class='table table-striped'>
<thead>
<tr>
<th>Date/Time</th>
<th>Exchange</th>
<th>Amount</th>
<th>Current reversed ex. rate</th>
<th>Arbitrage opportunity</th>
<th>Change</th>
</tr>
</thead>
<tbody>
<form action='arbitrage.php' method='post'>
<tr>
<td> 2015-12-24 22:32:50 </td>
<td>JPY to GBP</td>
<td>¥18,000.00 --> £100.80</td>
<td>179.48 GBP / JPY</td>
<td><font color='green'>¥<b>91.584</b> <b><u>PROFIT</u></b> on original ¥18,000.00 if you exchange now. <br/> (Total after change: ¥<b>18,091.584</b>).
</font></td>
<td><button type='submit'>Change</button></td>
</tr></form></tbody>
<tbody>
<form action='arbitrage.php' method='post'>
<tr>
<td> 2015-12-24 22:33:07</td>
<td>GBP to EUR</td>
<td>£15,000.00 --> €20,359.50</td>
<td>0.7365 EUR / GBP</td>
<td><font color='red'>£<b>5.228</b> <b><u>LOSS</u></b> on original £15,000.00 if you exchange now. <br> (Total after change: £<b>14,994.772</b>).
</font></td>
<td><button type='submit'>Change</button></td>
</tr></form></tbody>
To understand even better, this is an image of what the table looks like:
http://i.imgur.com/niyuT14.jpg
Now, when the 'Change' button is pressed, I want the information FROM THAT SPECIFIC ROW to be deleted from my SQL table called 'history'.
At the moment, I have tried things such as:
$query = "DELETE FROM history WHERE currency = ?", $row["currency"];
//row["currency"] is the stuff below the 'Exchange' header in the table.
When I press the 'Change' button however, all the existing rows of the HTML table get deleted from the 'history' SQL table. How do I get only one row to be deleted (the one where the button is pressed) while the others stay exactly where they are?
Please help!
Many thanks guys!
you can add hidden inputs with name='currency' for each row or more easily you can use ajax to submit your query
Change the form action form:
<form action='arbitrage.php' method='post'>
To
<form action='arbitrage.php?id=99' method='post'>
And update your query as:
$id = isset($_GET['id']) ? $_GET['id'] : ''; //This will give you--> id = 99;
$query = "DELETE FROM history WHERE currency = ?", $id;
The value 99 will be of course dynamic from db table.
I see that values are hardcoded and for both the buttons or forms you are using the same arbitrage.php action page. Use different pages for each form or button and write your mysql code as per your wish. And if it is dynamic then you will have to use the JS onClick event.
Instead of having so many forms, have just one. And then in the arbitrage.php, delete the submitted row and come back to the same page, may be..
<form action='arbitrage.php' name='changeForm' method='post'>
<input type="hidden" name="currency">
<table class='table table-striped'>
<thead>
<tr>
<th>Date/Time</th>
<th>Exchange</th>
<th>Amount</th>
<th>Current reversed ex. rate</th>
<th>Arbitrage opportunity</th>
<th>Change</th>
</tr>
</thead>
<tbody>
<tr>
<td> 2015-12-24 22:32:50 </td>
<td>JPY to GBP</td>
<td>¥18,000.00 --> £100.80</td>
<td>179.48 GBP / JPY</td>
<td><font color='green'>¥<b>91.584</b> <b><u>PROFIT</u></b> on original ¥18,000.00 if you exchange now. <br/> (Total after change: ¥<b>18,091.584</b>).
</font></td>
<td><button type='button' onclick="chg_currency('GBP / JPY');">Change</button></td>
</tr></tbody>
<tbody>
<tr>
<td> 2015-12-24 22:33:07</td>
<td>GBP to EUR</td>
<td>£15,000.00 --> €20,359.50</td>
<td>0.7365 EUR / GBP</td>
<td><font color='red'>£<b>5.228</b> <b><u>LOSS</u></b> on original £15,000.00 if you exchange now. <br> (Total after change: £<b>14,994.772</b>).
</font></td>
<td><button type='button' onclick="chg_currency('EUR / GBP');">Change</button></td>
</tr></tbody>
</table>
</form>
<script>
function chg_currency(c) {
document.forms['changeForm'].currency.value = c;
document.foms['changeForm'].submit();
}
</script>

How to get selected td value

I have a table with the image and image code data, show on code below:
<table id="tblForklift" cellpadding="5" cellspacing="0">
<tbody>
<tr id="image_info">
<td id="1W 1111">
<img src="../Client/images/forklift/corpus-christi-forklifts1.jpg" width="210px" height="210px"/>
<p style="text-align: center;">1W 1111</p>
</td>
<td id="2W 2222"></td>
<td id="3W 3333"></td>
</tr>
<tr id="image_info"></tr>
<tr id="image_info"></tr>
<tr id="image_info"></tr>
</tbody>
</table>
I tried using this code to get the html of selected td of the table. But it show "undefined".
$('#tblForklift').on('click', function(e) {
var forkliftCode = $('this').closest('tr').find('td').html();
alert(forkliftCode)
});
Since #tblForklift will match your table. You need to target td elements inside this table instead. Also if your elements has been added dynamically to the DOM, you can use event delegation:
$(document).on('click', '#tblForklift tr td', function(e) {
var forkliftCode = $(this).html();
alert(forkliftCode)
});
or better if your table is not added dynamically:
$('#tblForklift').on('click', 'tr td', function(e) {
var forkliftCode = $(this).html();
alert(forkliftCode)
});
Also some of your td are missing closing </td>
Add event to the td. so in each td click you can get html.
$('#tblForklift td').on('click',function(e) {
alert($( this ).html());
});
demo
id must be unique use class like,
HTML
<table id="tblForklift" cellpadding="5" cellspacing="0">
<tbody>
<tr class="image_info">
<td class="1W 1111 forklift">
<img src="../Client/images/forklift/corpus-christi-forklifts1.jpg" width="210px" height="210px"/>
<p style="text-align: center;">1W 1111</p>
</td>
<td class="2W 2222"></td>
<td class="3W 3333"></td>
</tr>
<tr class="image_info"></tr>
<tr class="image_info"></tr>
<tr class="image_info"></tr>
</tbody>
</table>
SCRIPT
$('.forklift').on('click', function(e) { // using class for multiple tds
var forkliftCode = $(this).find('p').text();
alert(forkliftCode);
});
Also, never give a space in a id, space has a different meaning in jquery selectors
Live Demo
HTML:
<td class="2W 2222">cvbcxbcvb</td>
<td class="3W 3333">bcvbcvbnvnv</td>
</tr>
<tr class="image_info"></tr>
<tr class="image_info"></tr>
<tr class="image_info"></tr>
</tbody>
</table>
jQuery:
$('#tblForklift td').click(function() {
alert($(this).html());
});

jquery datatable sorting not working for run time values

I used jquery data table for sorting. It works fine under normal condition. If i changed the value in run time, the sorting is not working.
This is my table data
<table width="94%" cellpadding="2" cellspacing="1" class="tablehead" id="pls-batting">
<thead>
<tr class="tab_head" align="right" id="pls-play" >
<th width="44" align="center" ># No </th>
</tr>
</thead>
<tbody>
<tr id="116706">
<td align="left" id='1' >test</td>
</tr>
<tr id="116707">
<td align="left" id='2'>bbb</td>
</tr>
<tr id="116708">
<td align="left" id='3' >xxx</td>
</tr>
</tbody>
</table>
Jquery method used for sorting is :
$(document).ready(function() {
$('#pls-batting').dataTable( {
} );
} );
By clicking the '# No' head the corresponding column displayed in asc and desc order respectively. These TD values will be changed onload by using
document.getElementById(3).innerHTML = 'something';
So as a result the 3rd column value is 'something'. So sorting will be done by this values. But it is not working.
It takes the old values. Please help me. Thanks
In DataTables, you should not update content of HTML cell. DT uses internal JavaScript array structure for searching/sorting and this cell is only a display value.
To update some cell you will need to use DT fnUpdate function see http://datatables.net/api#fnUpdate. Example of updating cell in the table is:
var oTable = $('#example').dataTable();
oTable.fnUpdate( 'New content', 10, 3 );
Note that cells are referenced by row/cell positions. If you don't know row/cell position then you can use http://datatables.net/api#fnGetPosition function to find position of TR with id 3 and use this info to update cell data using the fnGetData function (you can find example on the http://datatables.net/api#fnGetPosition)
Jovan

Categories