Pagination based on the result from dependent drop list - javascript

I am looking for a tutorial on pagination that only associates with the dependent drop list. In other words, If I made a selection from a dependent drop list with items, {Beavers, Cubs, Scouts, Venturers, Rovers and Leaders}. It will display the associated records and I was able to do that with ajax. However, some of those items have more than 100 records, and I would like to add pagination based on what was selected and can only find the tutorial that has drop list based of total number of record, example {50, 100, 250, 500, 5000 etc}
I have been searching using,
pagination based on the result from a dependent drop list ,
dependent drop list with pagination,
dynamic pagination with a drop list etc
with PHP, MySQL, js and ajax with no success. I am fairly new with this and a tutorial will help me understand better, Can anyone tell me what to look for? thanks
code for AdminPanelFrontEnd.php
<?php
require_once('includes/header.php');
require_once('includes/connection.php');
if(isset($_SESSION['admin']))
{
$query = "SELECT * FROM members";
$result = mysqli_query($con, $query);
}
else
{
header("location:AdminPanelFrontEnd.php");
}
?>
<script type = "text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js"></script>
<script>
function load_data(SectionID)
{
$.ajax({
type: "POST",
url: "AdminPanelBackEnd.php",
data: 'SectionID=' + SectionID,
success: function(data){
$("#details").html(data);
}
});
}
</script>
<div class="card-body">
<table class="table table-striped bg-info text-white" id="details" >
<tr>
Add Member
<div class="form-inline float-left ml-1">
<select class="form-control mb-2" id="section" onChange="load_data(this.value);">
<option value="null">Select Section</option>
<?php
$query = "SELECT * FROM sections ";
$result = mysqli_query($con, $query);
while($row=mysqli_fetch_assoc($result))
{
?>
<option value = "<?php echo $row["SectionID"]; ?>"> <?php echo $row["SectionName"]; ?> </option>
<?php
}
?>
</select>
</div>
</tr>
<tr class="bg-info text-white">
<td>Member Name</td>
<td>Member Email</td>
<td>Member Contact</td>
</tr>
</table>
</div>
code for AdminPanelBackEnd.php
<?php
require_once('includes/connection.php');
$query = "SELECT * FROM sections, members WHERE
sections.SectionID ='".$_POST["SectionID"]."' AND
sections.SectionID = members.SectionID ORDER BY MemberName
";
$result = mysqli_query($con, $query);
?>
<table class="text-center bg-info text-white">
<tr>
<td>Member Name</td>
<td>Member Email</td>
<td>Member Contact</td>
</tr>
<?php
while($row=mysqli_fetch_assoc($result))
{
$Member = $row['MemberName'];
$MemberEmail= $row['Email'];
$MemberContact = $row['Contact'];
?>
<tr class="bg-light text-dark">
<td><?php echo $Member ?></td>
<td><?php echo $MemberEmail ?></td>
<td><?php echo $MemberContact ?></td>
</tr>
<?php
}
?>
</table>

As you said, you already did the ajax, so the query string should be included in the paging navigation.
The link for next page should look like ?page=2&category=some_id
The ajax call will replace the whole content and the navigation.
There are libraries supporting that on every framework.

Related

Filter Dynamic Table using Multiple dropdown

Is there any way to filter my dynamic table using two dropdown? As for now, I only able to filter using only one dropdown. I cannot seem to find the right way so I'm gonna post my original code that successfully filter using one dropdown (because there are too many error in the latest code using two filter). Hope you can give me suggestions on how to solve this.
view.php
<?php
require "../model/model.php";
$month=$_GET['month'];
$sys = getSys(1)->fetch_assoc();
?>
<body>
<div class="row">
<table border="0">
<tr><td>
<select required class="form-control" name="month" id="month">
<option value="">-- Choose Month--</option>
<? echo getDropDownMonth($month) ;?>
</select>
</td></tr>
</table>
<table width="100%" class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th width="5%">No.</th>
<th width="20%">Date</th>
<th width="20%">Stock Code</th>
<th width="20%">Price(RM)/KG</th>
<th width="20%">QUANTITY(KG)</th>
<th width="20%">TOTAL(RM)</th>
</tr>
</thead>
<?
$i=1;
$raw = getRawMaterialListCode($month);
while($list_raw_material = $raw->fetch_assoc()) {
?>
<tr class="odd gradeX">
<td><?php echo $i; ?></td>
<td><?php echo $list_raw_material['date_received']; ?></td>
<td><?php echo $list_raw_material['stock_code'].' - '.$list_raw_material['stock_name']; ?></td>
<td><?php echo $list_raw_material['raw_price']; ?></td>
<td><?php echo $list_raw_material['in_per_kg']; ?></td>
<td><?php echo $list_raw_material['total_price']; ?></td>
</tr>
<?php $i++; } ?>
</table>
<script>
$(document).ready(function() {
$('#dataTables-example').DataTable({
responsive: true
});
$("#month").change(function(){
var selected_month=$(this).val();
sendType(selected_month);
});
});
function sendType(type)
{
window.location.href="view.php?month="+type;
}
</script>
</body>
model.php
function getRawMaterialListCode($month) {
$conn=db();
$sql = "
SELECT a.*
, c.stock_code
, c.stock_name
FROM avsb_raw_material a
LEFT
JOIN avsb_stock c
ON a.stock_code = c.stock_code
WHERE MONTH(a.date_received) = '$month'
ORDER
BY a.date_received
";
$result = $conn->query($sql);
return $result;
}
Supposedly I'm trying to add second dropdown as filter here:
<div class="row">
<table border="0">
<tr><td>
<select required class="form-control" name="month" id="month">
<option value="">-- Choose Month--</option>
<? echo getDropDownMonth($month) ;?>
</select>
**<select required class="form-control" name="stock_code" id="stock_code">
<option value="">-- Choose Stock--</option>
<? echo getDropDownStock($stock_code) ;?>
</select>**
</td></tr>
</table>
and the new model.php
function getRawMaterialListCode($month,$stock_code) {
$conn=db();
$sql = "
SELECT a.*
, c.stock_code
, c.stock_name
FROM avsb_raw_material a
LEFT
JOIN avsb_stock c
ON a.stock_code = c.stock_code
WHERE MONTH(a.date_received) = '$month'
AND a.stock_code = '$stock_code'
ORDER
BY a.date_received
";
$result = $conn->query($sql);
return $result;
}
Thanks in advance.
EDIT: These code are the closest one I try that did not have any error but the data still not display when filtering using two dropdown.
The url that i get :
http://localhost/stockcontrolsystem/view/view.php?month=10&stock_code=[object%20HTMLSelectElement]
view:
<?
$i=1;
$raw = getRawMaterialListCode($stock_code,$month);
while($list_raw_material = $raw->fetch_assoc()) {
?>
function:
$(document).ready(function() {
$("#month").change(function(){
var selected_month=$(this).val();
reloadMonth(selected_month);
});
$("#stock_code").change(function(){
if($("#month").val()==''){
alert('SELECT MONTH!');
$("#stock_code").val('');
}else{
var selected_stock=$(this).val();
var month = $("#month").val();
reloadStock(selected_stock,month);}
});
});
function reloadMonth(month){
//console.log(month);
location.href = "view.php?month="+month;
}
function reloadStock(selected_stock,month){
//console.log(obj);
location.href = "view.php?month="+month+"&stock_code="+stock_code;
}
ANSWERED! I try inserting what i found here and there and I finally SOLVED it.
$(document).ready(function() {
$("#month").change(function(){
var selected_month=$(this).val();
reloadMonth(selected_month);
});
$("#stock_code").change(function(){
if($("#month").val()==''){
alert('SELECT MONTH!');
$("#stock_code").val('');
}else{
var selected_stock=$(this).val();
var month = $("#month").val();
reloadStock(selected_stock,month);}
});
});
function reloadMonth(month){
//console.log(month);
location.href = "view.php?month="+month;
}
function reloadStock(selected_stock,month){
//console.log(obj);
location.href = "view.php?month="+month+"&stock_code="+selected_stock;
}

Hyperlinks is not working right for search result titles

I am trying to show search results from two tables. I have used union to put them together. Right now they work, when I search for something and matches, it shows up from both of the tables but I am having problem with the hyperlinks. Right now, for the search results it is always redirecting to grants individual when clicked on the title even for the results from art table. Please help, how do I make sure it goes to the right details page.
Controller
function searchResult() {
$keyword = $this->input->post('keyword');
$data['results'] = $this->products_model->searchResult($keyword);
$this->load->view($this->header)
$this->load->view('searchresults.php', $data);
$this->load->view('footer');
}
View
<br>
<table>
<?php if (!$results){ ?>
<h1> No results found. </h1>
<?php
}
else { ?>
<h2> Search Results </h2>
<?php
foreach($results as $row){ ?>
<br>
<table class="table">
<tr>
<td><h2><a href="<?= base_url()?>product/grantindividual/<?=$row->id?>"><?php echo $row->title?>
</h2></a></td>
</tr>
<tr>
<td><h2><a href="<?= base_url()?>product/artcallindividual/<?=$row->id?>"><?php echo $row-
>title?></h2></a></td>
</tr>
</table>
<?php }
}
?>
<br>
You need to have a column to differentiate the results, no need for adding an actual column in table itself, use dummy columns
Change this
$this->db->select($this->db->escape('v_grants') . ' AS source, id, Title');
To
$this->db->select($this->db->escape('v_grants') . " AS source, id, Title, 'grant' as type ");
Change this
$this->db->select($this->db->escape('v_art_call') . ', id, Title');
To
$this->db->select($this->db->escape('v_art_call') . ", id, Title, 'art' as type ");
Then you can easily use if-else statement to display the proper row (grant/art)
<table class="table">
foreach($results as $row){ ?>
if($row->type == 'grant'){ ?>
<tr>
<td><h2><a href="<?=base_url()?>product/grantindividual/<?=$row->id?>"><?php echo $row->title?>
</h2></a>
</td>
</tr>
<?php }elseif($row->type == 'grant') { ?>
<tr>
<td><h2><?php echo $row->title?></h2>
</td>
</tr>
<?php } ?>
<?php } ?>
</table>
You don't have a condition to differentiate the items from two tables.
<br>
<table>
<?php if (!$results){ ?>
<h1> No results found. </h1>
<?php
}
else { ?>
<h2> Search Results </h2>
<?php
foreach($results as $row){ ?>
<?php
if(!empty($row->source)){
$url = base_url()."product/grantindividual".$row->id;
}else{
$url = base_url()."product/artcallindividual".$row->id;
}
?>
<br>
<table class="table">
<tr>
<td>
<h2>
<?php echo $row->title;?>
</h2>
</td>
</tr>
</table>
<?php }
}
?>
<br>

How to solve slow loading page containing database information

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

Delete from database using javascript

I have a page containing a database table with all the rows and columns.
What I am trying to do is to select all the rows I want and then delete them when I click on the button.
This is what I've done so far in the table.php page:
<?php
include "config.php"; //connection to database
incude "home.js";
$funcao="Select * from palavras";
$result=mysqli_query($link, $funcao);
?>
<button id="button_apaga" type="button" onclick="delete()" > DELETE </button>
<?php if($result->num_rows > 0) { ?>
<table class="table">
<tr>
<th>IdPalavra</th>
<th>Palavra</th>
<th>Grau de Dificuldade</th>
<th>Data</th>
<th>Hora</th>
<th>Selecionar</th>
</tr>
<?php while($row = mysqli_fetch_assoc($result)) { ?>
<tr role="row">
<td><?php echo $row['idpalavras']; ?></td>
<td><?php echo $row['palavra']; ?></td>
<td><?php echo $row['graudificuldade']; ?></td>
<td><?php echo $row['data']; ?></td>
<td><?php echo $row['hora']; ?></td>
<td><input type="checkbox" name="check" id="checkbox" /></td>
</tr>
<?php } ?>
</table>
<?php }
else{
echo "0 resultados";
} ?>
JavaScript Page (home.js):
function delete(id){
var check = document.getElementById('checkbox');
if(check.checked) {
// sql query
}
My question is how can I do que sql query considering it's in a different page. Can I just open php and put the query inside?
Also how can I receive all the IDs from the selected rows to the function?
Thank you in advance.
One approach would be to use AJAX. For the purpose of condensing the code, I'm going to also incorporate jQuery into this solution. I am also going to change your checkbox to an individual button link for the sake of making this a bit less code. A solution to delete multiple at the same time could work similarly to this, but since you're using AJAX most likely this is going to be easier for your users.
Modify table.php
<?php
include "config.php"; //connection to database
incude "home.js";
$funcao="Select * from palavras";
$result=mysqli_query($link, $funcao);
?>
<?php if($result->num_rows > 0) { ?>
<table class="table">
<tr>
<th>IdPalavra</th>
<th>Palavra</th>
<th>Grau de Dificuldade</th>
<th>Data</th>
<th>Hora</th>
<th>Selecionar</th>
</tr>
<?php while($row = mysqli_fetch_assoc($result)) { ?>
<tr role="row" class="palavras_row">
<td><?php echo $row['idpalavras']; ?></td>
<td><?php echo $row['palavra']; ?></td>
<td><?php echo $row['graudificuldade']; ?></td>
<td><?php echo $row['data']; ?></td>
<td><?php echo $row['hora']; ?></td>
<td>Delete</td>
</tr>
<?php } ?>
</table>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js?ver=3.3.1"></script>
<script type="text/javascript">
(function($) {
$(document).on('click', '.palavras_row a.palavras_delete', function() {
var _id = $(this).attr('data-id');
var _row = $(this).parent().parent();
$.ajax({
url: 'delete.php',
data: {
idpalavras: _id
},
type: 'POST',
dataType: 'json',
success: function(__resp) {
if (__resp.success) {
_row.remove(); // Deletes the row from the table
}
}
});
});
})(jQuery);
</script>
Create a new file in the same folder as your table.php and name it delete.php
<?php
$idpalavras = filter_input(INPUT_POST, 'idpalavras', FILTER_SANITIZE_NUMBER_INT);
$success = false;
if ($idpalavras) {
include "config.php"; //connection to database
$funcao="delete from palavras where idpalavras = " . $idpalavras;
$result=mysqli_query($link, $funcao);
$success = true;
}
header('Content-Type: application/json');
echo json_encode(array('success' => $success));
The solution above sends a simple command to your PHP backend where the delete query can be run by PHP. You cannot run a mysql command directly from javascript since that is frontend code.
This code is a functional solution, but it is abbreviated; a more complete solution would have more detailed handling of potential errors (either via AJAX or processing your delete query). It should also have some security on your delete.php to make sure unauthorized users aren't able to delete records without the proper permission to do so.

Populating table with select dropdown (from database)

As shown in the code below, I have a dropdown list, populated from table "tabela". Below it I have a table which I need it to be populated depending on the option select from the dropdown?
How can I do this?
<div class="box">
<?php
$pdo = new PDO('mysql:host=localhost;dbname=dbname; charset=utf8', 'user', 'pass');
$sql = "SELECT id, pref, nome FROM tabela GROUP BY pref,nome ORDER BY nome";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$users = $stmt->fetchAll();
?>
<select>
<?php foreach($users as $user): ?>
<option value="<?= $user['id']; ?>"><?= $user['pref']; ?> - <?= $user['nome']; ?></option>
<?php endforeach; ?>
</select>
<table class="gradienttable">
<thead>
<tr>
<th colspan="7" class="tabelas">tipo1</th>
</tr>
<tr>
<th>Tipo1</th>
<th>Modelo</th>
<th>Qtde</th>
<th>Tipos</th>
<th>Pessoas</th>
<th>Vazios</th>
<th>Porcent</th>
</tr>
</thead>
<tbody>
<?php
foreach ($dbh->query("SELECT *, (ocupacao)*100 as ocupacao1 FROM tabela WHERE prefixo=8510") as $row) {
printf(
"<tr onmouseover='this.style.fontWeight=700;' onmouseout='this.style.fontWeight=400;'>
<td style='padding:8px;'>%s - %s</td>
<td style='padding:8px;'>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
</tr>",
$row->pref, $row->nome, $row->model, $row->qtde, $row->tipos, $row->pessoas, $row->vazios, $ocupacao1 = round($row ->ocupacao1 * 100)/100 . '%');
}
?>
</tbody>
</table>
</div>
I think first of all you should change your foreach() statement into:
<?php foreach($users as $user) { ?>
<option value="<? echo $user['id']; ?>"><? echo $user['pref']; ?> - <?echo $user['nome']; ?></option>
<?php }; ?>
I find this a bit more clean and readable :)
Then you will need to enable the page to "filter" the rows by select - this can be done either by posting the select contents each time you change the select value (so basically you create a form that will submit itself every time you change what is in select - not very modern solution) or use AJAX to send the contents and retrieve the results.
If you decide to go second option (which I would highly recommend) you should take a look at some tutorials on changing page content basing on AJAX response. I would recommend to go to jQuery for that - since you should find quite some functions there that would help you out...
Using the way you are gathering the data you need to echo the results into the html.
<?php foreach ($dbh->query("SELECT *, (ocupacao)*100 as ocupacao1 FROM infografico WHERE prefixo=8510") as $row) { ?>
<tr onmouseover='this.style.fontWeight=700;' onmouseout='this.style.fontWeight=400;'>
<td><?php echo $row->pref; ?></td>
...
</tr>
<?php } ?>
It would most likely be better to gather the data you need in the table first and form your array as required, then loop through that array and echo into the table.

Categories

Resources