Exclude Specific Columns when exporting data from HTML table to excel - javascript

I am using this script for exporting data from HTML table to Excel.
<script>
var tableToExcel = (function() {
var uri = 'data:application/vnd.ms-excel;base64,'
, template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'
, base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
, format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }
return function(table, name) {
if (!table.nodeType) table = document.getElementById(table)
var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}
window.location.href = uri + base64(format(template, ctx))
}
})()
</script>
I found this here
but when i export this data it includes all columns in HTML table as expected to do. but my last row contains some icons that i don't want to export to excel.
<div class="row" style="margin-left:20px;">
<div class="grid_4">
<div class="da-panel collapsible">
<input type="button" class="btn btn-success" onclick="tableToExcel('testTable', 'W3C Example Table')" value="Export to Excel" style="float:right">
<div class="da-panel-content">
<div class="da-panel-title" style="border-top:1px solid #ccc;border-bottom:1px solid #ccc">
<h3 style="padding-left:10px;font-weight:bold;">Staff Training Information</h3></div>
<table class="da-table da-ex-datatable-numberpaging" id="testTable" width="100%">
<thead width="100%">
<tr>
<th width="10%">Staff ID</th>
<th width="10%">Name</th>
<th width="10%">Location</th>
<th width="10%">POCT Test</th>
<th width="10%">Initial Training Date</th>
<th width="10%">Annual Competency Date</th>
<th width="10%">Competency Type</th>
<th width="1%">Next Competency Date</th>
<th width="39%">Action</th>
</tr>
</thead>
<tbody width="100%">
<?php
include_once('database.php');
$pdo = Database::connect();
$sql = 'SELECT * FROM competency';
foreach ($pdo->query($sql) as $row) {
$id = $row['staff_id'];
echo '<tr>';
echo '<td width="10%">'. $row['staff_id'] . '</td>';
$sql1 = "SELECT *FROM staff WHERE StaffID='$id'";
foreach($pdo->query($sql1) as $res)
{
echo '<td width="10%">'. $res['StaffName'] . '</td>';
}
echo '<td width="10%">'. $row['location'] . '</td>';
?>
<td width="10%">
<?php
$s = $row['poct_test'];
$val = explode(" ",$s);
for ($i=0; $i<sizeof($val); $i++)
{
$v = $val[$i];
echo $v."<br/>";
}
?>
</td>
<?php
echo '<td width="10%">'. $row['date_of_initial_training'] . '</td>';
echo '<td width="10%">'. $row['annual_competency'] . '</td>';
echo '<td width="10%">'. $row['type_of_competency'] . '</td>';
echo '<td width="1%">'. $row['next_competency'] . '</td>';
echo '<td width="39%">';
echo '<img src="images/ic_zoom.png" height="16" width="16" />';
echo ' ';
echo '<img src="images/icn_edit.png"/>';
echo ' ';
?>
<img src="images/icn_logout.png"/>
<?php
echo '</td>';
echo '</tr>';
}
Database::disconnect();
?>
</tbody>
</table>
</div>
</div>
</div>
</div>
As shown in code that last 3 echo contains update/delete icons. I just want to exclude Action column when exporting the table content in excel.
Any help would be highly appreciated.

You can use selectors from jQuery, clone of your table in memory then remove elements you don't want with appropriate selector.
var $table = $('#testTable').clone();
$table = filterNthColumn($table, 9); //remove Action column
function filterNthColumn($table, n){
return $table.find('td:nth-child('+n+'), th:nth-child('+n+')').remove();
}

make a hidden div under the table
<div class="exportData"> </div>
Then on click of the export button call export.php through ajax and put the result into exportData div. Then you can call your print script on the new data brought.
$.post( "export.php", function( data ) {
$( ".result" ).html( data );
});
Copy past your for loop on export.php and delete the two cols.

I think you can just clone the table firstly, remove the action column, and "tableToExcel" the cloned table.
To make the column removing easier, add class "action_th" to action th, and class "action_td" to action td.
Then it's like this,
var exTable = $('#testTable').clone();
//remove the action th/td
exTable.find('.action_th, .action_td').remove();
//then tableToExcel(exTable, ..

This works for me -
$('#divTableContainer').clone().find('table tr th:nth-child(7),table tr td:nth-child(7)).remove().end().prop('outerHTML')

Related

Post recordset to a table, then select one row and post to another page

I recently ran into a problem I wasn't quite sure how to solve. Sharing it here in case it helps someone else.
Use Case: User enters a string in a search box on a PHP page. On submit, the page queries the database and then posts results to a table on the same page. User then selects a single record with a radio button and needs to post only that record to a different PHP page. The second page does not have access to the database.
I took the actual page and created a sample page for clarity and testing, since the original had about 15 table columns.
<div class="container">
<div class="row" style="margin-top: 1rem;">
<div class="col-sm">
<form action="" method="post">
<table class="fit" id="entry">
<tr>
<td class="fit"><label for="start">Planet (try <strong>Caprica</strong> or <strong>Picon</strong>): </label></td>
</tr>
<tr>
<td class="fit"><input type="test" id="planet" name="planet" required autofocus /></td>
</tr>
</table>
<input class="btn btn-primary" type="submit" value="Get Characters" />
</form>
</div>
</div>
</div>
<div class="container" style="margin-top: 2rem;">
<div class="row">
<div class="col-sm">
<?php
require_once('./resources/pdo.php');
if ( isset($_POST['planet']) ) {
$planet = strtolower($_POST['planet']);
$pdo = new myPDO('phppostpost');
try {
$stmt = $pdo->prepare('CALL devCharacters(?)');
$stmt->bindParam(1, $planet, PDO::PARAM_STR);
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
die("Error occurred: " . $e->getMessage());
}
?>
<div class="table-responsive">
<table class="table table-striped table-hover">
<thead class="thead-light">
<tr>
<th class="fit">Select</th>
<th class="fit" scope="col">Customer First</th>
<th class="fit" scope="col">Customer Last</th>
<th class="fit" scope="col">Planet</th>
</tr>
</thead>
<tbody>
<?php while ($r = $stmt->fetch()): ?>
<tr>
<?php echo "<td class='fit'><input type='radio' id='cust-" . $r['customer_id'] ."' name='cust-id' value='". $r['customer_id'] . "' </td>"; ?>
<?php echo "<td class='fit'>" . $r['first_name'] . "</td>"; ?>
<?php echo "<td class='fit'>" . $r['last_name'] . "</td>"; ?>
<?php echo "<td class='fit'>" . $r['origin_planet'] . "</td>"; ?>
</tr>
<?php endwhile; ?>
</tbody>
</table>
</div>
<input class="btn btn-primary" onclick="getSelectedRowData();" type="submit" value="Send" />
<?php } ?>
</div>
</div>
</div>
As a relatively new developer, I couldn't figure out how to (1) grab just the selected row and (2) post data on submit from just that row, rather than from the the original search form.
After much Googling, as well as a kick in the pants from a Stack Overflow user who reminded me I needed to actually research for more than 20 minutes (thank you!), I was able to solve it.
I'll post the answer below for anyone else who runs into a similar problem.
To solve this, I used JavaScript to grab the selected row. In order to efficiently grab the correct record, I updated each TD element to have a unique, dynamically-generated ID:
<?php echo "<td class='fit' id='fname-" . $r['customer_id'] ."'>" . $r['first_name'] . "</td>"; ?>
<?php echo "<td class='fit' id='lname-" . $r['customer_id'] ."'>" . $r['last_name'] . "</td>"; ?>
<?php echo "<td class='fit' id='planet-" . $r['customer_id'] ."'>" . $r['origin_planet'] . "</td>"; ?>
I also gave the table body an ID so I could grab it quickly without grabbing a parent, then children, etc.:
<tbody id="results-body">
Finally, here's the JavaScript.
function getSelectedRowData() {
const tableRowArray = Array.from([document.getElementById('results-body')][0].rows);
let custFirst;
let custLast;
let custPlanet;
tableRowArray.forEach((tableRow, i) => {
cellButton = tableRow.getElementsByTagName('input');
if (cellButton[0].checked == true ) {
const rowID = cellButton[0].id.split('-').pop();
custFirst = document.getElementById('fname-' + rowID).innerHTML;
custLast = document.getElementById('lname-' + rowID).innerHTML;
custPlanet = document.getElementById('planet-' + rowID).innerHTML;
}
});
/* Build a hidden form solution to prep for post.
Source: https://stackoverflow.com/questions/26133808/javascript-post-to-php-page */
let hiddenForm = document.createElement('form');
hiddenForm.setAttribute('method', 'post');
hiddenForm.setAttribute('action', 'newpage.php');
hiddenForm.setAttribute('target', 'view');
const fieldCustFirst = document.createElement('input');
const fieldCustLast = document.createElement('input');
const fieldCustPlanet = document.createElement('input');
fieldCustFirst.setAttribute('type', 'hidden');
fieldCustFirst.setAttribute('name', 'custFirst');
fieldCustFirst.setAttribute('value', custFirst);
fieldCustLast.setAttribute('type', 'hidden');
fieldCustLast.setAttribute('name', 'custLast');
fieldCustLast.setAttribute('value', custLast);
fieldCustPlanet.setAttribute('type', 'hidden');
fieldCustPlanet.setAttribute('name', 'custPlanet');
fieldCustPlanet.setAttribute('value', custPlanet);
hiddenForm.appendChild(fieldCustFirst);
hiddenForm.appendChild(fieldCustLast);
hiddenForm.appendChild(fieldCustPlanet);
document.body.appendChild(hiddenForm);
// Post
window.open('', 'view');
hiddenForm.submit();
}
This worked for me, but I'm sure there's a better way to do this. Hopefully this (1) helps someone else and (2) a better solution is posted!
Here's a working demo: https://postfrompost.paulmiller3000.com/
Full source here: https://github.com/paulmiller3000/post-selected-from-post

Display All Table Rows that are Checked

I have a multiple column table with one column being checkboxes. If you check a checkbox then press the "Checkout" button, it will take the specified rows and display them in the body of an email.
I originally bring in the top 100 rows to keep the info light for the user. I also have a search functionality where the user can search for specific rows. While you can maneuver throughout different searches and still keep all of the checkboxes checked with session storage, when you hit "Checkout" it only displays the table rows that are checked and currently visible on the page. So, if I searched for a table row and checked it, but then went back to the original top 100 rows by clicking home, then that row would not display on the email.
How can I fix this and show ALL rows that have been checked, whether they are visible on the page or not?
HTML:
<section id="checkout-btn">
<button id="checkout" name="order" onclick="sendMail(); return false">Checkout</button>
</section>
<br>
<table id="merchTable" cellspacing="5" class="sortable">
<thead>
<tr class="ui-widget-header">
<th class="sorttable_nosort"></th>
<th class="sorttable_nosort">Loc</th>
<th class="merchRow">Report Code</th>
<th class="merchRow">SKU</th>
<th class="merchRow">Special ID</th>
<th class="merchRow">Description</th>
<th class="merchRow">Quantity</th>
<th class="sorttable_nosort">Unit</th>
<th style="display: none;" class="num">Quantity #</th>
</tr>
</thead>
<tbody>
<?php foreach ($dbh->query($query) as $row) {?>
<tr>
<td class="ui-widget-content"><input type="checkbox" class="check" name="check" id="checkid-<?php echo intval ($row['ID'])?>"></td>
<td class="loc ui-widget-content" data-loc="<?php echo $row['Loc'] ?>"><input type="hidden"><?php echo $row['Loc'];?></td>
<td class="rp-code ui-widget-content" align="center" data-rp-code="<?php echo $row['Rp-Code'] ?>" id="rp-code-<?php echo intval ($row['Rp-Code'])?>"><?php echo $row['Rp-Code'];?></td>
<td class="sku ui-widget-content" data-sku="<?php echo $row['SKU'] ?>" id="sku-<?php echo intval ($row['SKU'])?>"><?php echo $row['SKU'];?></td>
<td class="special-id ui-widget-content" data-special-id="<?php echo $row['Special-ID'] ?>" align="center" id="special-id-<?php echo intval ($row['Special-ID'])?>"><?php echo $row['Special-ID'];?></td>
<td class="description ui-widget-content" data-description="<?php echo htmlspecialchars($row['Description']) ?>" id="description-<?php echo intval ($row['Description'])?>"><?php echo $row['Description'];?></td>
<td class="quantity ui-widget-content" data-quantity="<?php echo $row['Quantity'] ?>" align="center" id="quantity-<?php echo intval ($row['Quantity'])?>"><?php echo $row['Quantity'];?></td>
<td class="unit ui-widget-content" data-unit="<?php echo $row['Unit'] ?>" id="unit-<?php echo intval ($row['Unit'])?>"><?php echo $row['Unit'];?></td>
<td style="display: none;" class="quantity_num ui-widget-content"><input type="textbox" style="width: 100px;" class="spinner" id="spin-<?php echo intval ($row['ID'])?>"></td>
</tr>
<?php } ?>
</tbody>
</table>
JavaScript for keeping checked checkboxes, checked, throughout the session:
$(function(){
$(':checkbox').each(function() {
var $el = $(this);
$el.prop('checked', sessionStorage[$el.prop('id')] === 'true');
});
$('input:checkbox').on('change', function() {
var $el = $(this);
sessionStorage[$el.prop('id')] = $el.is(':checked');
});
});
JavaScript that brings in data from table to email:
function sendMail() {
var link = "mailto:me#example.com"
+ "?subject=" + encodeURIComponent("Order")
+ "&body=";
var body = '';
$('table tr input[name="check"]:checked').each(function(){
var current_tr = $(this).parent().parent();
var data = current_tr.find('.loc').data('loc');
body += encodeURIComponent(data) + '\xa0\xa0';
var data =current_tr.find('.rp-code').data('rp-code');
body += encodeURIComponent(data) + '\xa0\xa0';
var data =current_tr.find('.sku').data('sku');
body += encodeURIComponent(data) + '\xa0\xa0';
var data =current_tr.find('.special-id').data('special-id');
body += encodeURIComponent(data) + '\xa0\xa0';
var data =current_tr.find('.description').data('description');
body += encodeURIComponent(data) + '\xa0\xa0';
var data =current_tr.find('.quantity').data('quantity');
body += encodeURIComponent(data) + '\xa0\xa0';
var data =current_tr.find('.unit').data('unit');
body += encodeURIComponent(data) + '\xa0\xa0';
var data =current_tr.find('.spinner').data('spinner');
body += encodeURIComponent(data) + '\xa0\xa0';
body += '%0D%0A';
});
body += '';
link += body;
console.log(link);
window.location.href = link;
}
Revised based your comments/new code:
Even with your new pasted code, the issue still remains that you can only output whats currently available on screen due looping over the table rows. Instead you need to take it a step further and build objects to house the information you need for building your email, then place those objects in storage for later retrieval.
Again looking at your code your checkboxes have a prefix of "check-id".
$('input:checkbox').on('change', function() {
var $el = $(this);
var key = $el.prop('id');
var rowObject = {};
//check if already in storage
if(sessionStorage.getItem(key) !== null){
rowObject = JSON.parse(sessionStorage.getItem(key));
rowObject.checkedVal = $el.is(':checked'); //update it's check value
}else{
//build entire row object
var current_tr = $(this).parent().parent();
rowObject.loc = current_tr.find('.loc').data('loc');
rowObject.rpCode = current_tr.find('.loc').data('rp-code');
rowObject.sku = current_tr.find('.loc').data('sku');
//etc. as many pieces as you need
}
//set to session
sessionStorage.setItem(key, JSON.stringify(rowObject));
});
//then later for your send email method
function sendEmail(){
var link = "mailto:me#example.com"
+ "?subject=" + encodeURIComponent("Order")
+ "&body=";
var body = '';
//loop over the row objects instead
$.each(sessionStorage, function(key, value){
//sort out the ones we want
if(key.indexOf("checkid-") > -1){
var rowObject = JSON.parse(sessionStorage.getItem(key));
body += encodeURIComponent(rowObject.loc + '\xa0\xa0');
body += encodeURIComponent(rowObject.rpCode + '\xa0\xa0');
body += encodeURIComponent(rowObject.sku + '\xa0\xa0');
//etc. as many pieces as you need
body += '%0D%0A';
}
});
//whatever other logic you have
}
I haven't fully tested this code for your purposes but you get the idea, build your objects then use those during your iteration.

PHP, how to get datepicker value from database if date != current date

I spend more than two days with no luck, when open site, its display all orders for current date. But sometimes I need to add order in previous date, after inserting, query return me to the index page and again its display the orders today, but i want now to display the last record which have different date.
code in index page:
<script>
$('#datepicker').change(function () {
$.post('check_data.php', {
dtpickerdate : $(this).val()
}, function (response) {
$('table').html(response);
});
});
$("#datepicker").datepicker({dateFormat: "mm-dd-yy",}).datepicker("setDate", new Date()).change();
</script>
insert query:
$conn->query("INSERT INTO `orders` VALUES('$order_no','$address','$no_ofppl','$d_time','$k_time','$date',now(),'$done','$mile')") or die('Error: ' . mysqli_error($conn));
echo '
<script type = "text/javascript">
alert("Saved Record");
window.location = "index.php";
</script>
'; }
}else
{
echo 'Result Error';
}
Check_data.php
<thead class = "alert-info">
<tr>
<th>Kitchen Time</th>
<th>Order#</th>
<th>First Name</th>
<th>Last Name</th>
<th>Address</th>
<th>Driver#</th>
<th>Delivery Time</th>
<th># of People</th>
<th>Miles</th>
</tr> </thead><tbody>
<?php
$dtpickerdate = isset($_POST['dtpickerdate']) ? $_POST['dtpickerdate'] : NULL;
$q_customer = $conn->query
("SELECT * from orders inner JOIN customer_order on customer_order.order_no =orders.order_no and orders.date like'$dtpickerdate' inner join driver_order on driver_order.order_no=orders.order_no LEFT JOIN customer on customer.phone=customer_order.phone order by k_time,time desc" )
or die(mysqli_error());
$k_time = '';
while($f_customer = $q_customer->fetch_array()){
$s=mysqli_num_rows($q_customer);
?>
<tr>
<?php
if($k_time == '' || $k_time != $f_customer['k_time']){
$k_time = $f_customer['k_time'];
echo '<td align="center" > <span style=" font-weight:bold;">'
.$f_customer['k_time']. '</td>';
} else{
echo "<td td style=' border: none;'> </td>";
}
echo "<td style='background-color: #5f5d5d; ' align='center' span style='font-weight:bold;'> <a href = '#' style='color:#ececec;font-weight:bold;' data-toggle = 'modal' data-target = '#action'>".$f_customer['order_no']."</a></td>";
echo "<td style='background-color: #5f5d5d;color:#ececec;'>" .$f_customer['first_name']."</td>";
echo "<td style='background-color: #5f5d5d;color:#ececec;'>". $f_customer['last_name']."</td>";
echo "<td style='background-color: #5f5d5d;color:#ececec;'>". $f_customer['address']."</td>";
echo "<td style='background-color: #5f5d5d;color:#ececec;'>". $f_customer['driver_no']."</td>";
echo "<td style='background-color: #5f5d5d;color:#ececec;'>". $f_customer['d_time']."</td>";
echo "<td style='background-color: #5f5d5d;color:#ececec;'>". $f_customer['no_ofppl']."</td>";
}

Submit Multiple, dynamically created forms but not all

So here we go. I have a page that lists a bunch of unscored sports games. Here is the query I run to generate the page.
<div id="NFL">
<?php
foreach ($conn->query("SELECT * FROM game_data WHERE sport='NFL' AND awayscore IS NULL ORDER BY date DESC") as $NFL) {
echo '<form method="post" action="update_score.php">
<table class="table table-bordered">
';
echo '
<thead>
<tr>
<th width="5%" class="head0">Rotation</th>
<th width="45%" class="head1">Team</th>
<th width="10%" class="head0">Money Line</th>
<th width="10%" class="head1">Spread</th>
<th width="10%" class="head0">Over/Under</th>
<th width="10%" class="head1">Score</th>
</tr>
</thead>';
echo '
<tr>
<td colspan="6">
';
$date = date_create($NFL['date']);
echo date_format($date, 'l F jS Y \# g:iA');
echo '
</td>
</tr>';
echo '
<tr>
<td>'.$NFL['awayrotation'].'</td>
<td>'.$NFL['awayteam'].'</td>
<td>'.$NFL['awaymoneyline'].'</td>';
echo '
<td>
';
if ($NFL['awaymoneyline'] > 0) {
$line = $NFL['line'] * -1;
echo $line;
}
elseif ($NFL['awaymoneyline'] < 0) {
echo $NFL['line'];
} ;
echo '
</td>';
echo '
<td>'.$NFL['total'].'</td>
<td><input type="text" required name="awayscore"></input></td>
</tr>';
echo '
<tr>
<td>'.$NFL['homerotation'].'</td>
<td>'.$NFL['hometeam'].'</td>
<td>'.$NFL['homemoneyline'].'</td>';
echo '
<td>
';
if ($NFL['homemoneyline'] > 0) {
$line = $NFL['line'] * -1;
echo $line;
}
elseif ($NFL['homemoneyline'] < 0) {
echo $NFL['line'];
} ;
echo '
</td>';
echo '
<td>'.$NFL['total'].'</td>
<td><input type="text" required name="homescore"></input></td>
</tr>';
echo '
<tr><td colspan="6" align="right"><input type="hidden" name="id" value="'.$NFL['id'].'"><span style="padding-right:15px"><input type="submit" value="Submit Score"></span></td></tr>
</table>
</form>';
}
?>
</div>
This is what I'm looking to do, I would like to have a button to submit multiple forms. Only though if they have placed a value in the score. Is this possible? I have read about doing multiple forms based off names but these forms are being created dynamically. I look forward to your insight.
here try this
I placed a counter that increments by one per SQL result processed This will also be a key we will use later
The counter is now added to the end of the name fields of the inputs (in front of a "-" to be exploded later)
At the bottom of the script is a little code how I would handle the back end information
<?php
$count = "0";
echo '<form method="post" action="update_score.php"><table class="table table-bordered">';
foreach ($conn->query("SELECT * FROM game_data WHERE sport='NFL' AND awayscore IS NULL ORDER BY date DESC") as $NFL) {
$count = $count+1;
echo '<thead>
<tr>
<th width="5%" class="head0">Rotation</th>
<th width="45%" class="head1">Team</th>
<th width="10%" class="head0">Money Line</th>
<th width="10%" class="head1">Spread</th>
<th width="10%" class="head0">Over/Under</th>
<th width="10%" class="head1">Score</th>
</tr></thead>';
echo '<tr><td colspan="6">';
$date = date_create($NFL['date']);
echo date_format($date, 'l F jS Y \# g:iA');
echo '</td></tr>';
echo '<tr><td>'.$NFL['awayrotation'].'</td><td>'.$NFL['awayteam'].'</td><td>'.$NFL['awaymoneyline'].'</td>';
echo '<td>';
if ($NFL['awaymoneyline'] > 0) {
$line = $NFL['line'] * -1;
echo $line;
}
elseif ($NFL['awaymoneyline'] < 0) {
echo $NFL['line'];
} ;
echo '</td>';
echo '<td>'.$NFL['total'].'</td><td><input type="text" required name="awayscore-$count"></input></td></tr>';
echo '<tr><td>'.$NFL['homerotation'].'</td><td>'.$NFL['hometeam'].'</td><td>'.$NFL['homemoneyline'].'</td>';
echo '<td>';
if ($NFL['homemoneyline'] > 0) {
$line = $NFL['line'] * -1;
echo $line;
}
elseif ($NFL['homemoneyline'] < 0) {
echo $NFL['line'];
} ;
echo '</td>';
echo '<td>'.$NFL['total'].'</td><td><input type="text" required name="homescore-$count"></input></td></tr>';
echo '<tr><td colspan="6" align="right"><input type="hidden" name="id-$count" value="'.$NFL['id'].'"><span style="padding-right:15px">';
}
echo '<input type="hidden" name="count" value="$count">'
echo '<input type="submit" value="Submit Score"></span></td></tr></table></form>'
// back end
$counter = 0;
while ($counter++ < $_POST['count'])
{
$name = $_POST["name-$counter"];
$awayscore = $_POST["awayscore-$counter"];
$homescore = $_POST["homescore-$counter"];
$id = $_POST["id-$counter"]; // considering you may need to get rid of the count
$name = explode("-", $name);
$name = $name[0];
// ect ect
// enter in to data base
//clear all data in strings
}
?>
Sorry about that this was due to haters :|
more to the point yes the back end code is for your passer (the code the form is pointed at)
NB: your PHP style is older than what most use now, close to what I use - just check that all tutorials you use give you references to PHP 5.3 and when in doubt go to php.net and check the function calls for version use - syntax and alternate options

Toggle the display of a table echod from php in Jquery

I have a table created in php that contains rows of customer information, with an additional row containing notes about each customer.
I would like a button above the table that when clicked will show or hide the notes row of each customer. So far my code doesn't seem to produce anything, I create the table here:
echo "<table id='listTable' border='1' cellpadding='10' class='listTable'>";
echo "<tr> <th>ID</th> <th>First Name</th> <th>Last Name</th> <th>Company Name</th> <th>Telephone</th> <th>Alt/ Telephone</th> <th>Address </th> <th>Town</th> <th>Postcode</th> <th></th> <th></th> <th></th> <th></th></tr>";
// loop through results of database query, displaying them in the table
for ($i = $start; $i < $end; $i++)
{
// make sure that PHP doesn't try to show results that don't exist
if ($i == $total_results) { break; }
// echo out the contents of each row into a table
echo "<tr class='main'>";
echo '<td>' . mysql_result($result, $i, 'id') . '</td>';
echo '<td>' . mysql_result($result, $i, 'First_Name') . '</td>';
echo '<td>' . mysql_result($result, $i, 'Surname') . '</td>';
echo '<td>' . mysql_result($result, $i, 'Company_Name') . '</td>';
echo '<td>' . mysql_result($result, $i, 'Telephone') . '</td>';
echo '<td>' . mysql_result($result, $i, 'Alt_Telephone') . '</td>';
echo '<td>' . mysql_result($result, $i, 'line_1') . '</td>';
echo '<td>' . mysql_result($result, $i, 'town') . '</td>';
echo '<td>' . mysql_result($result, $i, 'postcode') . '</td>';
echo '<td>View</td>';
echo '<td>Delete</td>';
echo '<td>archive</td>';
echo '<td>New Job</td>';
echo "</tr class='notes'>";
echo "<tr>";
echo '<td>' . mysql_result($result, $i, 'notes') . '</td>';
echo "</tr>";
}
// close table>
echo "</table>";
and Have the following Javascript at the top of my code
<link rel="stylesheet" type="text/css" href="test.css"/>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<html>
<head>
<title>View Records</title>
<script language="Javascript">
var rows = $('table.listTable tr.notes');
$('#showNotes').click(function() {
var showN = rows.filter('.showN').show();
rows.not( showN ).hide();
});
</script>
</head>
With the Toggle button created further down
<button id="showNotes">Toggle Notes</button>
When I click the button nothing is happening
You add class notes to close tag </tr>.
You have:
echo "</tr class='notes'>";
echo "<tr>";
Should be:
echo "</tr>";
echo "<tr class='notes'>";
And jQuery:
$(document).ready(function() {
$('#showNotes').click(function() {
$('#listTable tr.notes').toggle();
});
});
Now some remarks about your code:
Use mysqli_*, mysql_* is deprecated.
If you're using HTML in echo maybe try ' for it: echo '<tr class="notes">' looks better I think.
Use prepared statements: mysqli.prepare
Check this out (against your for loop): mysqli-stmt.fetch
Wrap the script in document ready function:
$(document).ready(function() {
$('#showNotes').click(function() {
var showN = rows.filter('.showN').show();
rows.not( showN ).hide();
});
});

Categories