Able to have div encompass part of table? - php

I'm making a table of games and times but I want to use javascript to show/hide part of the list. Once 5 games have been listed, all the games following that are to be encompassed within the div that will be showed/hidden by hitting a button. The trouble is, my div does not encompass ANY of the rows of the table, which is weird because the code says otherwise.
Am I not allowed to make a div that encompasses part of a table?
Thanks as always.
<table>
<?php
$result = #mysql_query('QUERY REMOVED');
$rows = mysql_num_rows($result);
$count = 0;
if ($rows == 0) {
echo '<h3> No games on this day </h3>';
} else {
while ($row = mysql_fetch_array($result)) {
**a bunch of variable assignments**
if($count == 5) echo '<tbody class="moreLess">';
echo '<tr><td>' . $awayteam . ' # ' . $hometeam . '</td><td>' . $time . '</td></tr>';
$count++;
}
if($count >= 6) echo '</tbody>';
}
?>
</table>
<div class="moreLessSwitch"><span>More [+]</span></div>
In case you wanted it, the javascript I use (tested and working)
$(function() {
$(".moreLess").hide();
$(".moreLessSwitch").toggle(function() {
$(this).html("<span>Less [-]</span>");
$(this).prevAll(".moreLess").slideDown();
}, function() {
$(this).html("<span>More [+]</span>");
$(this).prevAll(".moreLess").slideUp();
});
});
The table output HTML: http://pastebin.com/raw.php?i=99iUYq6j

No, a div can't exist between the table and tr tags.
However, you can (and should) use a tbody to delineate groups of tr.
Check out this fiddle.
[edit]
New fiddle.

tbody is correct way to define group of rows...
This test code works for me:
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="../jquery/jquery.js"></script>
<script type="text/javascript">
$(function(){
$(".moreLess").hide();
$(".moreLessSwitch").toggle(function() {
$(this).html("<span>Less [-]</span>");
$(".moreLess").slideDown();
}, function() {
$(this).html("<span>More [+]</span>");
$(".moreLess").slideUp();
});
})
</script>
</head>
<body>
<table>
<?php
$rows = array(array(1,2,3),array(1,2,3),array(1,2,3),array(1,2,3),array(1,2,3),array(1,2,3),array(1,2,3),array(1,2,3),array(1,2,3),array(1,2,3));
$count = 0;
if ($rows == 0) {
echo '<h3> No games on this day </h3>';
} else {
while ($row = array_pop($rows)) {
//**a bunch of variable assignments**
if($count == 5) echo '<tbody class="moreLess">' . "\r\n";
echo '<tr><td>' . $awayteam . ' # ' . $hometeam . '</td><td>' . $time . '</td></tr>' . "\r\n";
$count++;
}
if($count >= 6) echo "</tbody>\r\n\r\n";
}
?>
</table>
<div class="moreLessSwitch"><span>More [+]</span></div>
</body>
</html>

Your HTML is invalid. A <div> cannot occur inside a <table> unless inside a <td> cell, while yours spans several <tr> rows. A better solution would be to assign the .moreLess class to the table rows:
<tr class='moreLess'>
Your jQuery function then slides the table rows in and out of view.

Related

Custom simple pagination with jQuery and PHP - Finding myself stumped

So I'm working on my very first ever attempt at pagination (using simple Previous and Next buttons) on a for-fun project that I've undertaken. Below is all of the relevant code for my pagination system - I have left out the before and after, but I assure you that the table structure is valid.
Here is the jQuery I'm using with the elements I'm using to call the script:
<ul class="pager">
<li class="previous">< Previous</li>
<li class="next">Next ></li>
</ul>
<script>
$(document).ready(function() {
var page = 1;
$(".pagination-page").hide();
$(".pagination-page tbody[id=page" + page + "]").show();
$('#pagination-prev').click(function() {
page = page - 1;
$(".pagination-page").hide();
$(".pagination-page tbody[id=page" + page + "]").show();
});
$('#pagination-next').click(function() {
page = page + 1;
$(".pagination-page").hide();
$(".pagination-page tbody[id=page" + page + "]").show();
});
});
</script>
When I viewed the page without the jQuery active, I saw 8 <tbody> elements filled with dummy data that had been properly classed and id'd by the PHP script. My issue is that when I view the page with the script active, it doesn't seem to be working out for me. It hides all .pagination-page elements as I want, but my output has nothing toggled to show. Below is the PHP that is generating the content that I am flipping through.
<?php
try {
$listed = $dbc->query("SELECT data1,data2,data3,data4 FROM `table` ORDER BY data3 DESC")->fetchAll(PDO::FETCH_BOTH);
$annPP = 15;
$totalRows = count($listed);
$lastPCount = $totalRows % $annPP;
$totalPages = ceil($totalRows/$annPP);
$place = 0;
for ($i=1;$i<=$totalPages;$i++) {
echo "<tbody class='pagination-page' id='page{$i}'>";
if ($i == $totalPages) {
// Only do the remaining rows
$pageMax = $place + $lastPCount;
} else {
// Do 15 rows
$pageMax = $i * 15;
}
for ($j=$place;$j<$pageMax;$j=$place) {
$row = $listed[$j];
echo "<tr>
<td style='width: 25%'>";
if ($isAdmin) {
echo '<label class="control-label"><input type="checkbox" name="delete[]" value="' . $row['0'] . '"> ';
}
echo "<a href='view.php?id={$row[0]}'>{$row[1]}</a>";
if ($isAdmin) {
echo '</label>';
}
echo "</td>
<td style='width: 60%'>{$row[2]}</td>
<td class='text-center' style='width: 15%'>";
$created = new DateTime($row[3]);
echo $created->format('Y/m/d') . "</td>
</tr>";
$place++;
}
echo "</tbody>";
}
}
?>
What did I miss? What's going on? Thanks!
Removing the .pagination-page to make my jQuery read as follows:
$("tbody[id='page" + page + "']").show;
Fixed the problem. Not quite sure I understand why this is, though.

how to differentiate between these entries?

I have a new question about a project I had been working on. I was designing a grid with different colored cells. it has a hidden div which shows when a cell is clicked, however I realized that only one cell(the last one of it's type) will show. i.e. if I have 2 objects with the column "objaffinity" as 0 ("enemy") it will show both red cells on the grid, however only the last one will actually work.
how can I make it so that it will show the proper information for each cell?
here's my code:
mapgen.php:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="cellinfo.js"></script>
<script src="cmenu.js"></script>
<?php
require("sql.php");
$sql = <<<SQL
SELECT *
FROM `maps`
WHERE `objpresent` = 1
SQL;
if(!$result = $db->query($sql)){
die('There was an error running the query [' . $db->error . ']');
} // ran the query
//$xobj = array();
//$yobj = array();
$otype = array();
$oname = array();
$xyobj = array();
while($row = $result->fetch_assoc()){
$xyobj[$row['x']][$row['y']] = true;
$otype[$row['id']]=$row['objaffinity'];
$oname[$row['id']]=$row['object'];
}
// get the rows
$cellid=1;
//find whether the row is obstructed
for ($y = 0; $y < 20; $y++) {
echo '<tr>';
for ($x = 0; $x < 25; $x++) {
echo "<td>";
//Detect what type of object it is
if (isset($xyobj[$x][$y])) {
if($otype[$cellid] == 2)
{
echo "<a href='#'> <div class='foe'> </div><div class='foepopup'>";
echo $oname[$cellid];
echo "</div></a>";
}
elseif($otype[$cellid] == 1)
{
echo "<a href='#'><div class='friend'></div><div class='friendpopup'>";
echo $oname[$cellid];
echo "</div></a>";
}
else
{
echo "<a href='#'> <div class='neutral'></div><div class='neutralpopup'>";
echo $oname[$cellid];
echo "</div></a>";
}
$cellid++;
}
echo '</td>';
}
echo '</tr>';
}
?>
Cellinfo.js:
$(document).ready(function(){
//initially hide all popups
$(".foepopup").hide();
$(".neutralpopup").hide();
$(".friendpopup").hide();
//foebutton selected
$(".foe").on("click",function(e){
$(".friendpopup").hide();
$(".neutralpopup").hide();
$(".foepopup").show();
});
//close foe when selected
$(".foepopup").on("click",function(e){
$(".foepopup").hide();
});
//neutral button pressed
$(".neutral").on("click",function(e){
$(".foepopup").hide();
$(".friendpopup").hide();
$(".neutralpopup").show();
});
//close neutral
$(".neutralpopup").on("click",function(e){
$(".neutralpopup").hide();
});
//friend button pressed
$(".friend").on("click",function(e){
$(".foepopup").hide();
$(".neutralpopup").hide();
$(".friendpopup").show();
});
//close friend
$(".friendpopup").on("click",function(e){
$(".friendpopup").hide();
});
});
In your functions you use selectors, so for the script it does not matter which div was clicked.
Let me show you some examples:
$(".foepopup").on("click",function(e){
$(".foepopup").hide();
});
It should be something like this rather:
$(".foepopup").on("click",function(e){
$(this).hide();
});
And another example:
$(".neutral").on("click",function(e){
$(".foepopup").hide();
$(".friendpopup").hide();
$(".neutralpopup").show();
});
Rewrite it like this:
$(".neutral").on("click",function(e){
var td_tag = $(this).parent().parent();
td_tag.children(".foepopup").hide();
td_tag.children(".friendpopup").hide();
td_tag.children(".neutralpopup").show();
});
Rewrite other code on your own. this is the element on which click was triggered. td_tag will contain parent cell of a div clicked. After that, children method will allow you to find needed elements already inside specific cell.
Good luck!

Creating a table with mysql, php and ajax (with jquery)

For my new project i want the so modern approach of not needing to reload a page on every database request. :) I want the script to query the database and create a table with the query information.
I have tried different scripts i have found on the internet. The one below was closest to my needs.
index.php
<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>
<html xmlns='http://www.w3.org/1999/xhtml'>
<head>
<title>Display Page</title>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
<script language='JavaScript' type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js'></script>
</head>
<body>
<button type='button' name='getdata' id='getdata'>Get Data.</button>
<div id='result_table'>
</div>
<script type='text/javascript' language='javascript'>
$('#getdata').click(function(){
$.ajax({
url: 'getdata.php',
type:'POST',
dataType: 'json',
success: function(output_string){
$('#result_table').append(output_string);
} // End of success function of ajax form
}); // End of ajax call
});
</script>
</body>
</html>
getdata.php
<?php
include('conn.inc.php');
//Query of facebook database
$facebook = mysql_query('SELECT * FROM users')
or die(mysql_error());
//Output results
if(!$facebook)
{
mysql_close();
echo json_encode('There was an error running the query: ' . mysql_error());
}
elseif(!mysql_num_rows($facebook))
{
mysql_close();
echo json_encode('No results returned');
}
else
{
$output_string = '';
$output_string .= '<table border="1">';
while($row = mysql_fetch_assoc($facebook))
{
$output_string .= '<tr>';
foreach($row as $value)
{
$output_string .= '<td>{$value}</td>';
}
$output_string .= '</tr>';
}
$output_string .= '</table>';
}
mysql_close();
// This echo for jquery
echo json_encode($output_string);
?>
But i only get a table with a bunch of {$value} inside the table. I've tried with only $value but got a bunch of zeros.
I tried a simple script
$query = "SELECT users_name, users_password FROM users WHERE users_name = 'name'";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result);
echo $row['users_name'];
And then i get som results but with this script i have to refresh the page on every search. To be clear i want to be able to create a table with the information from a mysql database and display it on screen with reloading the page.
Any ideas?
You should just use $value instead of {$value}. You don't need another foreach loop inside the while loop.
$output_string = '';
$output_string .= '<table border="1">';
while($row = mysql_fetch_assoc($facebook))
{
$output_string .= '<tr>';
$output_string .= '<td>'.$row['Your table column name here'].'</td>';
$output_string .= '</tr>';
}
$output_string .= '</table>';
Instead of
$output_string .= '<td>{$value}</td>';
try
$output_string .= "<td>{$value}</td>";
i.e. replace the single quotes with double quotes.
See the doc here, which says:
When a string is specified in double quotes ... variables are parsed within it.
and
variables ... will not be expanded when they occur in single quoted strings.
You may invert the logic, and do it on client side, using a library that does that automatically, like http://phery-php-ajax.net
Instead of creating the table on the server side, send it as JSON to the browser, which is faster, and build your table:
Phery::instance()->set(array(
'load' => function(){
/* rest of mysql code */
$rows = array();
while($row = mysql_fetch_assoc($facebook)) { $rows[] = $row; }
return PheryResponse::factory()->json($rows);
})->process();
then in the client side inside $(function(){});
$(function(){
var $result_table = $('#result_table');
$result_table.phery('make', 'load');
$result_table.bind('phery:json', function(e, data){
var $this = $(this);
for (var i = 0; i < data.length; i++) {
$this.append($('<tr/>', {
'html': '<td>' + data[i].row_name + '</td>'
}));
}
});
$result_table.phery('remote');
});
100% WORKING
Just remove closing tags. E.g when opening a tag and store it in $output_string NEVER include the closing part...
Then don't include $value in quotation marks...
Put it outside quotation mark and then separate $value and closing quotation mark with dot the semi colon.

Working with MySQL and PHP to delete items on page

I am unsure of what path I should take for what I am wanting to do. The page loads some data from a mysql database with php. I made it so that a check box is generated with an incremented value starting wit 0 and so on for every value it finds in the database. What I am wanting to do is have that check box be so that when it is checked and they push the trashcan icon it will delete that row from the database. Where I am unsure is how to go about deleting it on button click and then reload the page. What would be the best way to do this? I am not needing the code or anything I just cant think of the best path to take to accomplish this.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Print Run</title>
<style type="text/css">
.openRun{
width:500px;
}
.openRun th{
text-align:center;
background-color:#CCC;
}
</style>
</head>
<body>
<div>
<?php
$totals = 0;
$i = 0;
$companyName = "";
$quantity = "";
$cardSize = "";
$dateAdded = "";
require("serverInfo.php");
$printRun = mysql_query("SELECT * FROM `printRun` WHERE status = 'Open'");
$row = mysql_fetch_array($printRun);
echo 'Print Run #: ' . $row['Run'];
$result = mysql_query("SELECT * FROM `printRun` WHERE status = 'Open'");
while($row = mysql_fetch_array($result)){
$companyName[$i] = $row['Company'];
$quantity[$i] = $row['Quantity'];
$cardSize[$i] = $row['Size'];
$dateAdded[$i] = $row['Date'];
$totals = intval($row['Quantity']) + $totals;
$i++;
}
$arraySize = count($companyName);
echo '<table class="openRun">';
echo '<tr><th>Company</th><th>Quantity</th><th>Size</th><th>Date Added</th><th></th></tr>';
for($i = 0; $i < $arraySize; $i++){
echo '<tr>';
echo '<td>' . $companyName[$i] . "</td>";
echo '<td>' . $quantity[$i] . "</td>";
echo '<td>' . $cardSize[$i] . "</td>";
echo '<td>' . $dateAdded[$i] . "</td>";
echo '<td><input type="checkbox" name="box'. $i .'" value="'. $i .'" /></td>';
echo '</tr>';
}
echo '<tr>';
echo '<td style="font-weight:bold; border-style:solid; border-top-width:1px;">Totals</td>';
echo '<td style="font-weight:bold; border-style:solid; border-top-width:1px;">' . $totals . "</td>";
echo '<td></td>';
echo '<td></td>';
echo '<td><img src="images/trash.png" /></td>';
echo '</tr>';
echo '</table>';
mysql_close($link);
?>
<br />
</div>
</body>
</html>
There's two ways of doing this. If you're not familiar with AJAX, or are scared about engaging with it, I'd suggest having a quick read of this tutorial just to get an overview.
With AJAX
If you don't want the page to reload, you're going to need to use AJAX to asynchronously send and receive data from the server. A typical example would be:
$('.trash_link').on('click', function() {
$.ajax({
url: 'path/to/script.php',
data: 'variable='+$('.input_class').val(),
dataType: 'html',
success: function(response) {
$('.container').html(response);
}
});
});
The crucial thing I'd advise is to put all of your layout logic in a controller or model function so that you don't repeat yourself. When data is sent to your server it can use this function to send back all your layout via the AJAX function. You can then insert the HTML inside your container element.
Without AJAX
All you do here is submit a form and your page reloads. For that reason you need to make sure you've already specified tags on your page. It really depends on what style you want your page to have - some people prefer reloads, some prefer the seamlessness of AJAX. Here is what you'd need if you chose to omit AJAX:
$('.trash_link').on('click', function() {
$('form').submit();
});
You can also add a pop-up confirmation if you want to:
$('.trash_link').on('click', function() {
if(confirm("Are you REALLY sure?") {
$('form').submit();
}
});
If you have an identifier in the table structure, you can just put
<input type='checkbox' name='ids[]' value='<?php echo $row['id']; ?>' />
Against every line of your table. Wrap the whole table in a form, make a submit button, in your script put something along these lines
if (isset($_POST['ids']) && is_array($_POST['ids'])) {
// some input sanitizing required.
$ids = array();
foreach ($_POST['ids'] as $id) if (intval($id) > 0) $ids[] = intval($id);
// $ids now hold the identifiers for the records to be deleted
if (count($ids)) $query = mysql_query("DELETE FROM `printRun` WHERE id IN (" . implode(', ', $ids) . ")");
// Then make a page refresh via HTTP 303 or otherwise to keep
// to the POST-redirect-GET policy.
header("HTTP/1.1 303 See Other");
header("Location: http://whate.ver/your_page_is.php");
}
If you just want a trash can that when clicked on, reloads the page and deletes the item, then just have that image in a link that passes along the id or whatever unique identifier the row has.
Delete
Have it hit a new php file that handles pulling off the unique identifier and deleting the record, then forwards back to the listing page.
$recordToDelete = is_numeric($_GET['id']) ? $_GET['id'] : null;
if($recordToDelete != null) {
$sql = "DELETE FROM `printRun` WHERE id = " . $recordToDelete;
//execute sql
}
//redirect back to listing page
header('Location: /yourpage.php');

Using jQuery to load a PHP Page in a div

I have this script:
<script type='text/javascript' src='js/jquery-1.4.4.mi.js'></script>
<script type='text/javascript'>
$('.filterMonth').change(function(){
alert('ijijiji');
$.ajax({
url: 'ajax/filterMandays.php',
//type: 'GET',
success: function(data){
//data is returned back
$('#mandayTable').html(data);
}
});
});
</script>
and this html:
<select name ="filterMonth">
<?php
$array_month = array("January","February","March","April","May","June","July","August","September","October","November","December");
foreach($array_month as $key => $month)
{
$value_month = $key+1;
echo "<option value = '$value_month'>$month</option>";
}
?>
</select>
-
<select name = "filterYear" onChange = "filter(filterMonth.value, filterYear.value)">
<?php
$curYear = date('Y');
for($i = 1990; $i<=$curYear+10; $i++)
{
if($i == $curYear)
{
echo "<option value = '$i' selected = 'selected'>$i</option>";
}
else
{
echo "<option value = '$i'>$i</option>";
}
}
?>
</select>
</td>
</tr>
</br>
</br>
<tr>
<div id="mandayTable"></div>
and this php page:
<?php
include("all.php");
$q = "SELECT md.mandays_id,md.employeenum,md.month,md.year,md.required_man_days,d.firstname,d.lastname
FROM tbl_mandays md,tbl_employee_details d
WHERE md.active = '1'
AND md.employeenum = d.employeenum
AND md.month = '10';";
$res = $db->Execute($q);
echo "<table border = 1>";
echo "<tr><th>Employee Number</th><th>First Name</th><th>Last Name</th><th>Month-Year</th><th>Required Man Days</th><th>Edit/Delete</th></tr>";
while($rows = $res->FetchRow())
//for($i=0;$i<5;$i++)
{
//iterating through // check if employee
// // if(isset($row[])) { }
$mandays_id = $rows[0];
$empnum = $rows[1];
$month_year = $rows[2] ."-" .$rows[3];
$required_man_days = $rows[4];
$firstname = $rows['month'];
$lastname = $rows[6];
//echo approvers here are not taken
//<a href=\"view_team.php?id=".$empnum."\" -> for someone to view the people beneath them (like org tree)
echo "<tr><td>".$empnum . "</td><td>".$firstname ."</td><td>".$lastname ."</td><td>" . $month_year ."</td><td>" .$required_man_days . "</td><td width = \"200\" align = \"center\"><a href = 'edit_mandays.php?mandays_id=$mandays_id');'>Edit/Delete</a></td></tr>";
}
echo "</table>";
?>
the script should basically load the php page in the div in the html once the "filterMonth" has been changed. but it doesn't work.
what seems to be the problem? :(
The selector in your jQuery is $('.filterMonth') but your select box doesn't have the filterMonth class. You need to change it to $('select[name=filterMonth]').
In order for the jQuery selector to contain your select, you need to make sure that it runs after the Select element is in the DOM (ie: lower down the HTML), or run your JavaScript once the document has finished loading, for example:
<script type='text/javascript' src='js/jquery-1.4.4.mi.js'></script>
<script type='text/javascript'>
jQuery(function() {
// do your DOM selections here, this function only runs once the document is loaded
});
</script>

Categories