Submit Multiple, dynamically created forms but not all - javascript

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

Related

Pagination does not work on page2 in php web page

Can someone help me on pagination syntax for php webpage. I have a set a pagination code to display 20 records per page. The records are displaying based on 'start date' and 'end date'.
The issue is, it works on page 1 but when I click on page 2 in pagination then it won't work. I assume the values of $_POST['startdate'] and $_POST['enddate] are not forwarding on page2.
<html>
<head>
<title></title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="multitab/bootstrap.min.css">
<link rel="stylesheet" href="css/font-awesome.min.css">
<style>
.inline{
display: inline-block;
float: right;
margin: 20px 0px;
}
input, button{
height: 34px;
}
</style>
</head>
<body>
<form id="form1" name="form1" action="" method="post">
<table>
<tr>
<td><b>Start date:</b></td>
<td><input type="date" id="startdate" name="startdate" size="10"> </td>
<td><b>End date:</b></td>
<td><input type="date" id="enddate" name="enddate" size="10" max=<?php echo date('Y-m-d');?>></td>
<td><input type="submit" value="Search" name="Search" onClick="return check()"></td>
</tr>
</table>
</form>
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("abc_db",$con);
$limit = 20;
if (isset($_GET["page"])) {
$pn = $_GET["page"];
}
else {
$pn=1;
};
if(isset($_POST['Search'])){
$startdate1 = $_POST['startdate'];
echo "Start date : ".$startdate1", ";
$enddate1 = $_POST['enddate'];
echo "End date : ".$enddate1;
}
$start_from = ($pn-1) * $limit;
$serial = (($pn-1) * $limit) + 1;
$today1= date("Y/m/d");
$days14_ago = date('Y/m/d', mktime(0, 0, 0, date("m") , date("d") - 14, date("Y")));
if ($startdate1 !=Null) {
$sql = "SELECT * FROM hd where datearrival='$startdate1' LIMIT $start_from, $limit";
} else if ($enddate1 !=Null) {
$sql = "SELECT * FROM hd where datearrival='$enddate1' LIMIT $start_from, $limit";
} else {
$sql = "SELECT * FROM hd where datearrival between '$days14_ago' and '$today1' LIMIT $start_from, $limit";
}
if (($startdate !=Null) && ($enddate !=Null)) {
$sql = "SELECT * FROM hd where datearrival between '$startdate1' and '$enddate1' LIMIT $start_from, $limit";
}
$rs_result = mysql_query ($sql);
?>
<div class="container">
<button style="height:25px;width:70px;" onclick="window.location.reload(true);">Refresh</button>
<br>
<div>
<font face='cambria'><p><span style="display:inline-block; margin-left: 650px; ">
</span></p> </font>
<font face="Cambria" size="2"> <table class="table table-striped table-condensed table-bordered">
<thead>
<tr>
<th width="5%" valign="top">Sr#</th>
<th width="10%" valign="top">Date arrival</th>
<th width="10%" valign="top">Pno</th>
<th width="10%" valign="top">First name</th>
<th valign="top"></th>
<th valign="top"></th>
</tr>
</thead>
<tbody>
<?php
while ($row = mysql_fetch_array($rs_result, MYSQL_ASSOC)) {
$pno1=$row['pno'];
$datearrival1=$row['datearrival'];
$sr_num = $serial++;
?>
<tr>
<td><?php echo $sr_num; ?></td>
<td><?php echo date("d/m/Y", strtotime($row['datearrival'])); ?></td>
<td><?php echo $row["pno"]; ?></td>
<td><?php echo $row["first_name"]; ?></td>
<td><p align="center">edit</font></td>
<td><p align="center">delete</font></td>
</tr>
<?php
};
?>
</tbody>
</table>
</font>
<div>
<ul class="pagination">
<?php
$sql = "SELECT COUNT(*) FROM hd where datearrival between '$startdate1' and '$enddate1'";
$rs_result = mysql_query($sql);
$row = mysql_fetch_row($rs_result);
$total_records = $row[0];
$total_pages = ceil($total_records / $limit);
$k = (($pn+4>$total_pages)?$total_pages-4:(($pn-4<1)?5:$pn));
$pagLink = "";
if($pn>=2){
echo "<li><a href='qm.php?page=1'> << </a></li>";
echo "<li><a href='qm.php?page=".($pn-1)."'> < </a></li>";
}
for ($i=-4; $i<=4; $i++) {
if($k+$i==$pn)
$pagLink .= "<li class='active'><a href='qm.php?page=".($k+$i)."'>".($k+$i)."</a></li>";
else
$pagLink .= "<li><a href='qm.php?page=".($k+$i)."'>".($k+$i)."</a></li>";
};
echo $pagLink;
if($pn<$total_pages){
echo "<li><a href='qm.php?page=".($pn+1)."'> > </a></li>";
echo "<li><a href='qm.php?page=".$total_pages."'> >> </a></li>";
}
?>
</ul>
<div class="inline">
<input id="pn" type="number" min="1" max="<?php echo $total_pages?>"
placeholder="<?php echo $pn."/".$total_pages; ?>" required>
<button onclick="go2Page();">Go</button>
</div>
</div>
</div>
</div>
<script>
function go2Page()
{
var pn = document.getElementById("pn").value;
pn = ((pn><?php echo $total_pages; ?>)?<?php echo $total_pages; ?>:((pn<1)?1:pn));
window.location.href = 'qm.php?page='+pn;
}
/* start and end date- validation checks */
function check(){
var startdatea=document.getElementById("startdate").value;
var enddatea=document.getElementById("enddate").value;
if(Date.parse(startdatea)>Date.parse(enddatea)){
alert("Please select a different End Date.");
return false;
}
}
</script>
</body>
</html>
$_POST superglobal variable is populated by PHP when a POST HTTP request is processed. This is the case on the request for page 1.
However, your go2page() function is mutating location.href, which generates a GET HTTP request, and so does pagination links.
You should append your startdate and enddate params to the pagination URLs, to forward your params to the next/previous requests :
qm.php?page=<YOUR-PAGE-NUMBER>&startdate=<YOUR-START-DATE>&enddate=<YOUR-END-DATE>';
And use $_GET['startdate'] and $_GET['enddate] to retrieve those when processing GET requests.
More about $_POST https://www.php.net/manual/en/reserved.variables.post.php
More about GET AND POST HTTP requests : https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods
There's an error in your isset($_POST['Search'])
your code:
if(isset($_POST['Search'])){
$startdate1 = $_POST['startdate'];
echo "Start date : ".$startdate1", ";
$enddate1 = $_POST['enddate'];
echo "End date : ".$enddate1;
}
possible working solution:
if(isset($_POST['Search'])){
$startdate1 = $_POST['startdate'];
echo "Start date : ".$startdate1.", ";
$enddate1 = $_POST['enddate'];
echo "End date : ".$enddate1;
}
Though I didn't try it yet, but I assume this is the cause, pagination in page2 will not work since the code is not executed after the error which is the pagination for page2.
EDIT: The . fixes things.
echo "Start date : ".$startdate1", ";
is different than
echo "Start date : ".$startdate1.", ";
Add values of your $_POST inside links and use them as $_GET so you would use both.
$startdate1=$enddate1=null; //to hide notice
if(isset($_POST['Search'])){
$startdate1 = $_POST['startdate'];
echo "Start date : ".$startdate1.", ";
$enddate1 = $_POST['enddate'];
echo "End date : ".$enddate1;
} else if (!empty($_GET['startdate']) && !empty($_GET['enddate'])){
$startdate1 = $_GET['startdate'];
echo "Start date : ".$startdate1.", ";
$enddate1 = $_GET['enddate'];
echo "End date : ".$enddate1;
}
$pagLink .= "<li><a href='qm.php?page=".($k+$i)."&startdate=".startdate1."&enddate=".$enddate1."'>".($k+$i)."</a></li>";
For your need:
$pagLink = "";
if($pn>=2){
echo "<li><a href='qm.php?page=1&startdate=".startdate1."&enddate=".$enddate1."'> << </a></li>";
echo "<li><a href='qm.php?page=".($pn-1)."&startdate=".startdate1."&enddate=".$enddate1."'> < </a></li>";
}
for ($i=-4; $i<=4; $i++) {
if($k+$i==$pn)
$pagLink .= "<li class='active'><a href='qm.php?page=".($k+$i)."&startdate=".startdate1."&enddate=".$enddate1."'>".($k+$i)."</a></li>";
else
$pagLink .= "<li><a href='qm.php?page=".($k+$i)."&startdate=".startdate1."&enddate=".$enddate1."'>".($k+$i)."</a></li>";
};
echo $pagLink;
if($pn<$total_pages){
echo "<li><a href='qm.php?page=".($pn+1)."&startdate=".startdate1."&enddate=".$enddate1."'> > </a></li>";
echo "<li><a href='qm.php?page=".$total_pages."&startdate=".startdate1."&enddate=".$enddate1."'> >> </a></li>";
}
That would help you to move dates to next page.
You need to set it to all paging links. Also you can make extra if statement to not pass empty GET
EDIT:
As I already told: You need to set it to all paging links. Also you can make extra if statement to not pass empty GET (that includes javascript)
function go2Page()
{
var pn = document.getElementById("pn").value;
pn = ((pn><?php echo $total_pages; ?>)?<?php echo $total_pages; ?>:((pn<1)?1:pn));
window.location.href = 'teztz.php?page='+pn+'&startdate=<?=startdate1;?>&enddate=<?=$enddate1;?>';
}

How to write on the server data edited by the client

I want a Select Box where I can Filter the Data from the Database (with Ajax - no site reload). For example: Order the data by ID or Order the data by name
Thats working fine and now when I get that data I want also that I can edit the data with Inputs and save it (also trough ajax) but I dont know how. I know how to save data with ajax but not when the data is a response from another ajax.
Code: (Its not well formatted here, that's why pastebin: http://pastebin.com/7mgi6VMc)
Index:
<div class="wrapper">
<p id="result">Erfolgreich gespeichert!</p>
<br>
<div class="filter">
<form>
Anzeige:
<select class="selectFilter" onchange="filterFunction(this.value)">
<option value="id_back">ID - Aufwärts</option>
<option value="id_up">ID - Abwärts</option>
</select>
</form>
</div>
<br>
<br>
<div id="resultCatalogue">
<b>Bitte wähle die gewünschte Anzeige ...</b>
</div>
</div>
getData.php:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css? family=Open+Sans" />
<script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
$("#save").on("submit", function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "./save.php",
data: $(this).serialize(),
success: function(data) {
if($('#result').css('display') == 'none') {
document.getElementById('result').style.display = 'block'
} else {
document.getElementById('result').style.display = 'none'
setTimeout(function() {
document.getElementById('result').style.display = 'block'
}, 100);
}
},
});
});
</script>
</head>
<body>
<?php
$type = intval($_GET['type']);
if($type == "id_up")
{
echo '
<table class="tableCatalogue">
<tr>
<th class="th" width="5%">ID</th>
<th class="th" width="5%">Unter-ID</th>
<th class="th" width="15%">Titel</th>
<th class="th" width="5%">Iceron</th>
<th class="th" width="10%">Sichtbar</th>
<th class="th" width="10%">Aktiv</th>
<th class="th" width="5%">Min. Rank</th>
<th class="th" width="5%">VIP</th>
<th class="th" width="5%">Reihen Nummer</th>
<th class="th" width="10%">Layout</th>
</tr>
<form method="post" id="save">
';
$index = 0;
$getCataloguePages = mysql_query("SELECT * FROM catalog_pages");
while($row = mysql_fetch_array($getCataloguePages))
{
$id = $row['id'];
$parent_id = $row['parent_id'];
$caption = $row['caption'];
$icon_image = $row['icon_image'];
$visible = $row['visible'];
$enabled = $row['enabled'];
$min_rank = $row['min_rank'];
$min_vip = $row['min_vip'];
$order_num = $row['order_num'];
$page_layout = $row['page_layout'];
$i++;
if(IsEven($i)){
$even = "Even";
} else {
$even = "Odd";
}
echo '
<tr>
<td class="td'.$even.'" width="5%"><input placeholder="ID" class="inputTable" name="id[]" value="'.$id.'"></td>
<td class="td<?php echo $even; ?>" width="5%"><input placeholder="Unter-ID" class="inputTable" name="parent_id[]" value="'.$parent_id.'"></td>
<td class="td<?php echo $even; ?>" width="15%"><input placeholder="Titel" class="inputTable" name="caption[]" value="'.$caption.'"></td>
<td class="td<?php echo $even; ?>" width="5%"><input placeholder="Icon" class="inputTable" name="icon_image[]" value="'.$icon_image.'"></td>
<td class="td<?php echo $even; ?>" width="5%"><select placeholder="Sichtbar" class="selectTable" name="visible[]"><option value="1">Sichtbar</option><option value="0">Nicht sichtbar</option></select></td>
<td class="td<?php echo $even; ?>" width="5%"><select placeholder="Aktiviert" class="selectTable" name="enabled[]"><option value="1">Aktiv</option><option value="0">Nicht aktiv</option></select></td>
<td class="td<?php echo $even; ?>" width="5%"><select placeholder="Mindest Rank" class="selectTable" name="min_rank[]"><option>1</option></select></td>
<td class="td<?php echo $even; ?>" width="5%"><select placeholder="VIP" class="selectTable" name="min_vip[]"><option value="1">Nur VIP</option><option value="0">Alle</option></select></td>
<td class="td<?php echo $even; ?>" width="5%"><input placeholder="Reihen Nummer" class="inputTable" name="order_num[]" value="'.$order_num.'"></td>
<td class="td<?php echo $even; ?>" width="10%"><input placeholder="Layout" class="inputTable" name="page_layout[]" value="'.$page_layout.'"></td>
</tr>
';
$index++;
}
echo '
<input class="save" type="submit" name="save" value="Speichern">
<br><br>
</form>
</table>
';
?>
<script>
$("#save").on("submit", function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "./save.php",
data: $(this).serialize(),
success: function(data) {
if($('#result').css('display') == 'none') {
document.getElementById('result').style.display = 'block'
} else {
document.getElementById('result').style.display = 'none'
setTimeout(function() {
document.getElementById('result').style.display = 'block'
}, 100);
}
},
});
});
</script><?php
}
?>
save.php:
$size = count($_POST['id']);
$i = 0;
while ($i < $size)
{
$id = $_POST['id'][$i];
$query = "UPDATE catalog_pages SET id = '".$id."' LIMIT 1";
mysql_query($query) or die ("Error in query: $query");
++$i;
}
Like I said, everything is included. Database Connection, all fine.
It is also showing me the Response with the Select but then I want to Update that data - also with ajax.
Where do I have do place the Ajax Code? How can I do that?

sum of rows is not updated when running AJAX code until F5 refresh

Following this link here about sending data into MySQL using AJAX, I have this output:
What I want, is to see the row with the curent rows shown in the div and not at the bottom. And how to refresh the sum, and not wait to refresh the page ?
Here is the final AJAX code:
function addFunction()
{
var selectW = $('#insert_new').val();
var selectW = $('#selectW').val();
var select_at = $('#select_at').val();
var pay = $('#pay').val();
var facture = $('#facture').val();
var select_opt = $('#select_opt').val();
if(pay!="")
{
$.ajax({
data: {'selectW': selectW, 'select_at': select_at, 'pay': pay, 'facture': facture, 'select_opt': select_opt},
type: "post",
url: "insert_buy.php",
success: function(response){
if(response=="success")
{
$('#incident_table').append('<tr><td height="30" align="center">' + selectW + '</td><td align="center">' + select_at + '</td> <td align="center" dir="ltr">' + pay + '</td> <td align="center">' + facture + '</td> <td align="center"><form action="delete.php" method="post"><input type="hidden" name="rowid" value="" /><input class="imgClass_dell" type="submit" onclick="return confirm(\'هل أنت متأكد؟\')" name="delete_sales" value="" /></form></td></tr>');
alert(data);
$('#selectW').val('');
$('#select_at').val('');
$('#pay').val('');
$('#facture').val('');
$('#select_opt').val('');
}
else
{
alert("No Data added");
}
},
error: function(){
//alert('error; ' + eval(error));
}
});
}
else
{
alert("All Fields Are Required!!");
}
}
And here is where PHP calculate the sum:
</tr>
</form>
<?php
$sum = 0;
$selectAll = "SELECT * FROM sales WHERE date_now = :date ORDER BY date_now DESC, time_now DESC";
$stmtAll=$conn->prepare($selectAll);
$stmtAll->bindValue(':date', date("y-m-d"));
$execAll=$stmtAll->execute();
$result=$stmtAll->fetchAll();
?>
<?php foreach($result as $rows){
$sum = $sum + $rows['pay'];
//var_Dump($rows) ?>
<tr>
<td height="30" align="center"><?php echo $rows['type'] ?></td>
<td align="center"><?php echo $rows['provider'] ?></td>
<td align="center" dir="ltr"><?php echo (number_format($rows['pay'], 0, ',', ' ')). ' L.L'?></td>
<td align="center"><?php echo $rows['facture'] ?></td>
<td align="center"><form action='delete.php' method="post">
<input type="hidden" name="rowid" value="<?php echo $rows['id'] ?>" />
<input class="imgClass_dell" type="submit" onclick="return confirm('هل أنت متأكد؟')" name="delete_sales" value="" />
</form></td>
</tr>
<?php } ?>
<tr>
<th colspan="4" align="center" bgcolor="#666666">المجموع</th>
<td dir="ltr" bgcolor="#666666" align="center"><?php
echo ($sum = number_format($sum, 0, ',', ' ')). ' L.L';
?></td>
</tr>
</table>
</div>
</div>
I hope I can get some help.
you can try with this
You'll need a getTable.php page that displays your table, and nothing else: no headers, footers, etc.
PHP (getTable.php) - this can be any server side code (asp, html, etc..)
<?php
echo '<table><tr><td>TEST</td></tr></table>';
?>
Then, in your JS, you can easily refresh the table by using the load() method:
HTML
<div id="tableHolder"></div>
js
<script type="text/javascript">
$(document).ready(function(){
refreshTable();
});
function refreshTable(){
$('#tableHolder').load('getTable.php', function(){
setTimeout(refreshTable, 5000);
});
}
</script>
try and good luck i prefer work with jqgrid

I'm trying to pull data from database into selectboxes

I'm trying to pull data from database into selectboxes, but when the data is pulled it goes into one 'td' and not into separate td's. I'm trying to achieve result as shown below
but I keep getting this result
here is my code
<?php
$data_array = array();
$result2 = mysql_query("SELECT * FROM `firefightersonscene`
JOIN `firefighterinfo` ON `firefightersonscene`.`FireFighterInfo_fighterID` = `firefighterinfo`.`fighterID`
JOIN `stationlocation` ON `firefighterinfo`.`StationLocation_locationID`=`stationlocation`.`locationID`
WHERE `IncidenceOfFire_incidentID`='$getIncID' ORDER BY `firstName`");
if(mysql_num_rows($result2) > 0)
{
while($rows2 = mysql_fetch_object($result2))
{
$data_array[] = $rows2;
}
}
?>
<form action="core_viewfireoccurrence.php?incidentID=<?php echo $rows->incidentID; ?>" method="post" class="view_occurrence_form">
<table id="myTable">
<thead>
<tr>
</tr>
</thead>
<tbody>
<tr>
<td class="count">1</td>
<td>
<?php
foreach($data_array as $rows2):
$fighterID = $rows2->FireFighterInfo_fighterID;
$results = mysql_query("SELECT `fighterID`, `firstName`, `middleName`, `lastName`, `stationlocation`.`exactlocation`
FROM `firefighterinfo`
JOIN `stationlocation` ON `firefighterinfo`.`StationLocation_locationID`=`stationlocation`.`locationID` ORDER BY `firstName`");
echo '<select name="fireman[]" required><option value=""></option>';
while($row = mysql_fetch_array($results))
{
if($row['fighterID'] == $fighterID)
echo '<option selected>'. $row['firstName']." ".$row['middleName']." ".$row['lastName'].", ".$row['exactlocation'].'</option>';
else
echo '<option>'. $row['firstName']." ".$row['middleName']." ".$row['lastName'].", ".$row['exactlocation'].'</option>';
}// end while
echo '</select><br>';
endforeach;
?>
</td>
<td>
<input type="button" value="X" class="removeVar"/>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>
<input type="button" id="addVar" value="Add Item"/>
</tr>
</tfoot>
</table>
</form>
JS CODE
<script type="text/javascript">
$('form').on('click', '.removeVar', function(){
$(this).closest('tr').remove();
$('.count').each(function(i){
$(this).text(i + 1);
});
});
//add a new node
$('#addVar').on('click', function(){
var varCount = $('#myTable tr').length - 1;
$node = ['<tr>',
'<td class="count">'+varCount+'</td>',
'<td><select name="fireman[]" class="ctlGroup" required>',
'<option value=""></option>',
'<?php require("php/fireman_list.php"); ?>',
'</select></td>',
'<td><input type="button" value="X" class="removeVar"/>',
'</td></tr>'].join('\n');
$('#myTable > tbody:last').append($node);
});
</script>
You need to put your whole table row in the loop. You will also need to add a variable to count the row number for you.
<?php
$row =1;
foreach($data_array as $rows2):
?>
<tr>
<td class="count"><?php echo $row; ?></td>
<td>
<?php
$fighterID = $rows2->FireFighterInfo_fighterID;
$results = mysql_query("SELECT `fighterID`, `firstName`, `middleName`, `lastName`, `stationlocation`.`exactlocation`
FROM `firefighterinfo`
JOIN `stationlocation` ON `firefighterinfo`.`StationLocation_locationID`=`stationlocation`.`locationID` ORDER BY `firstName`");
echo '<select name="fireman[]" required><option value=""></option>';
while($row = mysql_fetch_array($results))
{
if($row['fighterID'] == $fighterID)
echo '<option selected>'. $row['firstName']." ".$row['middleName']." ".$row['lastName'].", ".$row['exactlocation'].'</option>';
else
echo '<option>'. $row['firstName']." ".$row['middleName']." ".$row['lastName'].", ".$row['exactlocation'].'</option>';
}// end while
echo '</select><br>';
?>
</td>
<td>
<input type="button" value="X" class="removeVar"/>
</td>
</tr>
<?php
$row++;
endforeach;
?>

Exclude Specific Columns when exporting data from HTML table to excel

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')

Categories