So I have an SQL query which pulls all data from a mysql table, called example:
function get_example($conn){
$statement = "SELECT * FROM `example`";
if ($result = $conn->query($statement)) {
$rows = array();
while($row = $result->fetch_array()){
$rows[] = $row;
}
return $rows;
} else {
return 0;
}
}
I call this function in PHP and store the value in $example. I can then use a foreach to create a table of everything:
<table>
<tr>
<td>ID</td>
<td>Name</td>
<td>Description</td>
</tr>
<?php
foreach($example as $entry){
echo "<tr>";
echo "<td>" . $entry['id'] . "</td>";
echo "<td>" . $entry['name'] . "</td>";
echo "<td>" . $entry['description'] . "</td>";
echo "</tr>";
}
?>
</table>
This is all simple enough and I can use a form with method POST to choose a value and filter the table accordingly (for eg, only show entires where the description field is a certain value).
My question is, how do I filter this table using JS?
I would want to have html buttons which, when clicked, call a function which changes the relevant tags css property for visibility from hidden to visible.
So - by default every tag is listed int he table with visibility proeprty set to hidden. Then, when certain elements are clicked, the associated elements are set to visible.
Is this possible? My JS knowledge is limited so the more I look into it, the more it seems the PHP form may be the ssafest way to go
Thanks
If you want the Filtering in your table with the help of JavaScript. the i suggest Datatables for it.
DataTables:
DataTables is a plug-in for the jQuery Javascript library. It is a highly flexible tool, based upon the foundations of progressive enhancement, and will add advanced interaction controls to any HTML table.
You Can find More Example on datatables here
HTML
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<?php
foreach($example as $entry){
<tr>
<td><?php $entry['id']; ?></td>
<td><?php $entry['name']; ?></td>
<td><?php $entry['description']; ?></td>
</tr>
}
?>
</tbody>
</table>
Js
$(document).ready(function() {
$('#example').DataTable();
});
Add this cdn links to your page
https://code.jquery.com/jquery-1.12.0.min.js
https://cdn.datatables.net/1.10.11/js/jquery.dataTables.min.js
https://cdn.datatables.net/1.10.11/css/jquery.dataTables.min.css
If you choose to filter objetcs client-side using javascript you could use array.filter() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
or the usefull library underscorejs http://underscorejs.org/
Related
On one page that contains links to the database on my website, the page loads very slowly, is there any way to speed up the loading of that page?
I tried it on the server and when there were no visitors just import database and it immediately slowed down loading the page.
You can inspect the page via my website: https://translatesubtitles.com/browse_subtitle.php or check the page code:
I think it may be up to the database table to slow it down, you can look at the table code below:
<div class="row">
<table id="example" data-order='[[ 0, "desc" ]]' class="table table-striped " style="width:100%">
<thead>
<tr>
<th style="display: none">ID</th>
<th>Name</th>
<th>Language</th>
<th>Author</th>
</tr>
</thead>
<tbody>
<?php
include("my.php");
$query = "SELECT * FROM me order by id DESC";
$result = mysqli_query($conn, $query);
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_array($result)){
?>
<tr>
<td style="display: none"><?php echo $row['id']; ?></td>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['language']; ?></td>
<td><?php echo $row['author']; ?></td>
</tr>
<?php }} ?>
</tbody>
</table>
</div>
Have you already added id as an index to the table? If not, adding one should help.
ALTER TABLE `me` ADD INDEX `id` (`id`)
You might also be able to cut down on the amount of data that's transferred by selecting only the columns that you need. E.g.
SELECT id, name, language, author FROM me ORDER BY id DESC
I'm trying to give user option to choose how data to be displayed- table or list style. Is this possible by switching buttons? Is it better to be done with page reload or dinamically with DOM manipulation? I'm a rookie still with Javascript and jQuery and need a little push here. Thanks!
EDIT:
For example I want all table tags to be switched with divs or ul.
This is a common Wordpress post loop.
Here is my code:
<?php if ( have_posts() ) : ?>
<table class="table table-striped table-hover">
<thead>
<tr>
<th>Title</th>
<th>Picture</th>
<th>Category</th>
</tr>
</thead>
<tbody>
<?php while ( have_posts() ): the_post();?>
<tr>
<td><?php the_title(); ?></td>
<td><?php the_post_thumbnail(); ?></td>
<td><?php echo strip_tags(get_the_term_list( $post->ID, 'my-taxonomy', '', ', ' )); ?></td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
You could simply use the button to add a layout classname to a parent element and use CSS to override the default styles.
So, perhaps your default layout is list:
.mystuff {
/* list-styles */
}
... and later, for the table-layout:
.mystuff.table {
/* override CSS for table-layout */
}
I found this solution:
http://bootsnipp.com/snippets/featured/list-grid-view
It works perfectly for me, as I use Bootstrap framework.
I have a html table that is populated using PHP:
<table class="flat-table flat-table-1" width="100%">
<tr style="background-color:#FFF;">
<td class="table-head">Name</td>
<td class="table-head">Review</td>
<td class="table-head">Rating</td>
</tr>
<?php
//run a query to find all the fields in the review table that belong to the specific hall, using the id in the url ($current_id)
if ($r = $db->prepare("SELECT * FROM reviews WHERE hall_id = :current_id")) {
//bind the parameters used in the above query using the 'current_id' variable
$r->bindParam(':current_id', $current_id);
//Execute the prepared query
$r->execute();
//search review table for all fields and save them in $review
$reviewtemp = $r->fetchAll();
foreach( $reviewtemp as $review) {
//loop and output the reviews
?>
<tr>
<td><? echo $review['name'];?></td>
<td><? echo $review['review']; ?></td>
<td><? echo $review['overall']; }}?></td>
</tr>
</table>
The - <td><? echo $review['review']; ?></td>' - contains longs pieces of text that need to be shorted using a show more/less button, if the piece of text is over 400 characters.
I have tried using pieces of code I have found on the internet but have had no luck. I am hoping that maybe somebody on here can point me in the right direction? I am happy to use any solution I can.
The following piece of code is the kind of thing I need to use, however I am unsure how to implement it into my code: http://jsfiddle.net/Wpn94/326/
(--I have previously asked a similar question before but had no responses. I have now changed the question and have posted it again--)
In the following code, I updated the HTML to contain more than one review and use tables.
http://jsfiddle.net/3VTb7/
The structure that is impotant for the javascript to work is this:
<table>
<tr><td>Name</td></tr>
<tr><td><div class="content hidecontent">insanely long review here</div><div class="show-more">Show More</div><td></tr>
</table>
Note: You must have the hidecontent class. The show more div should be directly after the content you want to hide and include the show-more class.
Without looking at the code you tried to mix together, I cannot determine what else can be wrong.
This might be an error: <td><? echo $review['overall']; }}?></td>
Since you're looping the table rows, } should go after </tr>
<tr>
<td><? echo $review['name'];?></td>
<td><? echo $review['review']; ?></td>
<td><? echo $review['overall']; ?></td>
</tr>
<?php }} ?>
To answer question, maybe something like:
First, if you have review_id use that otherwise add $id = 0; before if ($r = $db->prepare("...
Split review into two..
<td><?php
$review = $review['review'];
$short_length = 200;
$short = substr($review, 0, $short_length);
$long = substr($review, $short_length);
$id++;
echo $short . '<span class="content hidecontent" id="review'.$id.'">'.$long.'</span>
Show More';
?></td>
Then use jQuery to toggle
$("#hidecontent").click(function(){
var reviewid = "#review"+$(this).data("id");
$(reviewid).slideToggle(500, function(){
var moreless = $(reviewid).is(":visible") ? 'Less' : 'More';
$(this).html("Show "+moreless)
});
});
I am trying to work with Tablesorter but it doesn't seem to work when I output the table using PHP.
My PHP code:
function displayHours() {
include 'dbinfo.php';
global $name;
$date = $_SESSION["selectedDate"];
$result = mysqli_query($con, "SELECT * FROM hours WHERE name='$name' AND date='$date'");
echo '<thead><tr>
<th><center>Project name</th>
<th><center>Hour(s)</th>
</tr></thead>';
$color = FALSE;
while($row = mysqli_fetch_array($result))
{
if (!$color) {
echo "<tbody><tr>";
$color = TRUE;
} else if ($color) {
echo "<tbody><tr class=\"alt\">";
$color = FALSE;
}
echo "<td> " . $row['projectName'] . "</td>";
echo "<td> " . $row['description'] . "</td>";
echo '</tr> ';
echo '</tbody>';
}
}
My html code:
<div class="datagrid">
<table id="myTable" class="tablesorter">
<?php displayHours();?>
</tbody>
</table>
</div>
My jQuery code:
$(document).ready(function () {
$("#myTable").tablesorter();
});
If I output two in one loop it at least sorts them, but once I only make it one it wont do anything.
I tried everything, any help please?
There is no problem with the tablesorter, but your table html. You PHP code generates thead and several tbody tags. Normally there should be one tbody tag.
To fix that in your PHP before your while loop in put tbody opening and after your loop close the tag.
//open tbody tag
echo "<tbody>";
while($row = mysqli_fetch_array($result)){
//print rows
}
//close tbody tag
echo "</tbody>";
There is also an unnecessary tbody closing in your "html code", it's better to remove it.
<div class="datagrid">
<table id="myTable" class="tablesorter">
<?php displayHours();?>
</table>
</div>
Then your tablesorter would be working smoothly.
I know while using tablesorter myself. I had to use
$(table).trigger("update")
to get a dynamically added table to update, however this wasn't with php.
I have an HTML form on a wordpress based site that allows users to see database records that match the inputs of the form. Using AJAX based on this tutorial http://www.w3schools.com/ajax/ajax_aspphp.asp I have a javascript that uses a GET on a php script on the server. however the javascript is not permitted to run by XSS protection the console output is as follows
The XSS Auditor refused to execute a script in 'page' because its source code was found within the request. The auditor was enabled as the server sent neither an 'X-XSS-Protection' nor 'Content-Security-Policy' header.
Is this caused by how my javascript is invoked?
Source:
<html>
<head>
<script>
function showUser(degreecourse, Interest, gradyear){
var xmlHttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("info").innerHTML=xmlhttp.responseText;
}
else{document.getElementById("info").innerHTML}="Error";
}
xmlhttp.open("GET","/getcandidates.php?q=degreecourse=" + escape(degreecourse) + "&Interest=" + escape(Interest) + "&gradyear=" + escape(gradyear),true);
xmlhttp.send();
return false;
}
</script>
</head>
<body>
Filter By:
<form >
<table>
<tbody>
<tr>
<td>Degree Course:</td>
<td><select name="degreecourse" onchange = "showUser(document.getElementById('degreecourse').value, document.getElementById('Interest').value, document.getElementById('gradyear').value)">
<option>Any</option><option>Archaeology</option><option>Biochemistry</option><option>Biology</option><option>Biomedical Sciences</option><option>Chemistry</option><option>Computer Science</option><option>Economics</option><option>Education</option><option>Electronics</option><option>English</option><option>Environmental Studies</option><option>History</option><option>History of Art</option><option>Language and Linguistic Studies</option><option>Law</option><option>Management</option><option>Mathematics</option><option>Medicine</option><option>Music</option><option>Nursing, Midwifery and Healthcare</option><option>Philosophy</option><option>Physics</option><option>Politics</option><option>Politics, Economics and Philosophy</option><option>Psychology</option><option>Social Policy and Social Work</option><option>Social and Political Sciences</option><option>Sociology</option><option>Theatre, Film and Television</option></select></td>
</tr>
<tr>
<td>Interest:</td>
<td><select name="Interest" onchange = "showUser(document.getElementById('degreecourse').value, document.getElementById('Interest').value, document.getElementById('gradyear').value)">
<option>Any</option><option>Management</option><option>Marketing<option>Technical</option>
</select>
</td>
</tr>
<tr>
<td>Graduating After:</td><td><input id="gradyear" type="number" value=2013 name="gradyear" onchange = "showUser(document.getElementById('degreecourse').value, document.getElementById('Interest').value, document.getElementById('gradyear').value)"/></td>
</tr>
</tbody>
</table>
</form>
<br>
<div id="info"><b>Person info will be listed here.</b></div>
</body>
</html>
The PHP file returns a HTML table as follows after connecting to the database.
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Degree Subject</th>
<th>Email Address</th>
<th>Graduating Year</th>
<th>Interest</th>
<th>CV</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['Forname'] . "</td>";
echo "<td>" . $row['Surname'] . "</td>";
echo "<td>" . $row['DegreeSubject'] . "</td>";
echo "<td>" . $row['EmailAddress'] . "</td>";
echo "<td>" . $row['GraduatingYear'] . "</td>";
echo "<td>" . $row['Interest'] . "</td>";
echo "<td><form action='www.yorkcommunityconsulting.co.uk/CVs/".$row['CVurl']."><input type='submit' value='See CV'></form></td>";
echo "</tr>";
}
echo "</table>";
The escape() function was deprecated in JavaScript version 1.5. Use encodeURI() or encodeURIComponent() instead. I'm not sure It'll get you where you want, but may solve at least part of your problem.
Have you tried using jQuery (GET/load) instead of plain JS to see if you get the same result ?
You have an <option> tag that is not not properly closed (see "Marketing")
I'm no JS guru but, didn't you have to close your "else" a bit later ? like after the: "Error"; instead of before the "=" sign ?
else{document.getElementById("info").innerHTML="Error";}
instead of
else{document.getElementById("info").innerHTML}="Error";