Is it possible to do this pagination without backgrid? - javascript

I'm trying to implement server side pagination like datetable and I found backbone.paginator library, I don't know if there is something else.
Through their examples they used another library to help accomplishing this which is backgrid.js and its paginator plugin
Is it possible to do this pagination without Backgrid? Could you please add any example on this?

I developed the following code to share with you A JS/php code that do server site pagination and you could change it according to your need and later i may summarize it better.
First make connection to DB and create pagination table:
CREATE TABLE `pagination` (
`id` INT( 16 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`name` VARCHAR( 50 ) NOT NULL ,
`age` INT( 3 ) NOT NULL ,
`company` VARCHAR( 50 ) NOT NULL
)
Second insert 400 same records :
$i=0;
while ($i< 400){
$pag="insert into pagination (id,name,age,company) VALUES
('NULL','john','40','google')";
$excu=$mysqli->query($pag);
$i++;
}
Then make test.php
<!DOCTYPE html>
<html><head>
<style>
#container{overflow-x: hidden;max-width:90%;min-width:90% ;margin: 0 auto;}
td{max-width:10%;min-width:10%}
tr,td{border:1px solid black }
#page{display:inline;border:1px solid black}
#numb,#numbs{display:none}
.button{background:white}
</style>
</head>
<body >
<?php $defaultoption ="10";?>
<div id=container></div><span id=numb></span><span id=numbs><?php echo
$defaultoption;?></span>
<script type=text/javascript src=js.js></script>
</body>
</html>
Then make js.js :
onload = function (){
var container=document.getElementById("container");
var table =document.getElementById("numbs").innerHTML;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
container.innerHTML=xhttp.responseText;
var button=document.getElementById("button");
button.children[0].disabled="true";
button.children[0].style.background="yellow";
}}
xhttp.open("POST", "testa.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("table="+table);
}
function select(){
var sel =document.getElementById("select");
var table=sel.options[sel.selectedIndex].value;
var b2 =document.getElementById("numbs");
b2.innerHTML=table;
var se = new XMLHttpRequest();
se.onreadystatechange = function() {
if (se.readyState == 4 && se.status == 200) {
document.getElementById("container").innerHTML=se.responseText;
var button=document.getElementById("button");
button.children[0].disabled="true";
button.children[0].style.background="yellow";
}}
se.open("POST", "testa.php", true);
se.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
se.send("table="+table);
}
function button(button){
var b2 =document.getElementById("numbs");
var b1 =button.innerHTML;
var numb = document.getElementById("numb");
numb.innerHTML=b1;
var b= b2.innerHTML;
var butt = new XMLHttpRequest();
butt.onreadystatechange = function() {
if (butt.readyState == 4 && butt.status == 200) {
document.getElementById("container").innerHTML=butt.responseText;
var d = document.getElementsByClassName("button");
for(i=0;i<d.length;i++){
if(d[i].innerHTML == numb.innerHTML){d[i].disabled="true";
d[i].style.background="yellow";
}}}}
butt.open("POST", "testa.php", true);
butt.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
butt.send("b="+b+"&b1="+b1);
}
Make testa.php :
<?php
$pag="SELECT * FROM pagination ORDER BY id ASC ";
$exc=$mysqli->query($pag);
$numrwos =mysqli_num_rows($exc);
if($_POST['b']){
$b =$_POST['b'];
$b1 =$_POST['b1'];
$max=($b*$b1);
$m =($b1-1);
$n =($m*$b);
$min =($n-1);
if($numrwos){
echo "<select id=select onchange=select()><option selected=selected>Show Entries</option>";
if($numrwos < 11){
echo "<option>10</option>";
}elseif($numrwos > 10 && $numrwos < 26){
echo "<option>10</option><option>25</option>"; }elseif($numrwos > 25 &&
$numrwos < 51){
echo "<option>10</option><option>25</option><option>50</option>";}else{
echo "<option>10</option><option>25</option><option>50</option>
<option>100</option>";}
echo "</select><br />";
echo "<table width=80% id=table>";
echo "<tr><td width=10%>id</td><td>name</td><td>age</td><td>company</td></tr>";
$stop="0";
while ($result=mysqli_fetch_array($exc)){
if($stop > $min && $stop < $max){
echo "<tr><td>".$result['id']."</td><td>".$result['name']."</td>
<td>".$result['age']."</td><td>".$result['company']."</td></tr>";
}else{}
$stop++;
}echo "</table><br />";
echo "<div id=button>";
$i=0;
while($i < $numrwos){
$page+=$i % $b == $b-1;
$i++;
if($i%$b == 1){
$pagenum=$page+1;
echo "<button class=button onmouseover='button(this)'>".$pagenum."</button>";}}
echo "</div>";
}else{echo "no records";}
}else{
$t =$_POST["table"];
if($numrwos){
echo "<select id=select onchange=select()><option selected=selected>Show Entries</option>";
if($numrwos < 11){
echo "<option>10</option>";
}elseif($numrwos > 10 && $numrwos < 26){
echo "<option>10</option><option>25</option>"; }elseif($numrwos > 25 && $numrwos < 51){
echo "<option>10</option><option>25</option><option>50</option>";}else{
echo "<option>10</option><option>25</option><option>50</option>
<option>100</option>";}
echo "</select><br />";
echo"<table width=80% id=table>";
echo "<tr><td width=10%>id</td><td>name</td><td>age</td><td>company</td></tr>";
$stop="0";
while ($result=mysqli_fetch_array($exc)){
echo "<tr><td>".$result['id']."</td><td>".$result['name']."</td>
<td>".$result['age']."</td><td>".$result['company']."</td></tr>";
if($stop ==$t-1){break;}
$stop++;
}echo "</table><br />";
echo "<div id=button>";
$i=0;
while($i < $numrwos){
$page+=$i % $t == $t-1;
$i++;
if($i%$t == 1){
$pagenum=$page+1;
echo "<button class=button onmouseover='button(this)'>".$pagenum."</button>";}}
echo "</div>";
}else{echo "no records";}
}
?>
I wish that help you .

I did it
in the View initialize function
I call
this.reloadCustomPages();
here its implementation
reloadCustomPages: function(options) {
var self = this;
self.block();
self.customPages.fetch({data: $.param(options)}).always(function () {
self.unblock();
});
}
in the server side (java spring) I modified the api to accept new query strings
#RequestParam(value = "pageNumber", defaultValue = "1"),
#RequestParam(value = "perPage", defaultValue = "10")
and instead of returning the list directly it returns useful pagination info like
total number of items in database
current page nuber
page size
and the items itself
check this server-side snippet (I know it's not related but worthy to look at)
#RequestMapping(value = "/editor/pages", method = RequestMethod.GET)
public void listPages(#RequestParam(value = "pageNumber", defaultValue = "1") Integer pageNumber,
#RequestParam(value = "perPage", defaultValue = "10") Integer perPage,
HttpServletResponse httpResp) throws IOException {
Long recordsTotal = pageSvc.findTotalNumberOfPages();// select count(*) from table_name
List<PbCustomPage> pages = pageSvc.findPages(pageNumber, perPage);// server side query that gets a pagenated data
BackbonePaginatorResponse response = new BackbonePaginatorResponse();// I created this simple class
response.setTotalCount(recordsTotal);
response.setPageNumber(pageNumber);
response.setPerPage(perPage);
response.setItems(pages);
httpResp.setContentType("application/json");
json.createCustomPageSerializer().addProperties().serialize(response, httpResp.getWriter());// just make your server send that obkect
}
now back the function call it will till the server to get page 1 with a page size of 10
in my template, I have this
<div class="pagination clear" style="text-align: center;">
<%= customPages.paginationHtml %>
</div>
let me tell you how I populate it
customPages.paginationHtml = this.generatePagination(customPages);
and here is the most important part
generatePagination: function (paginationResponse) {
var currentPage = paginationResponse.pageNumber,
lastPage = paginationResponse.totalCount==0?1:Math.ceil(paginationResponse.totalCount/paginationResponse.perPage);
var html = '<ul class="pagination">';
html += '<li class="'+(currentPage == 1?"disabled":"")+'" data-pb-page-number="1">««</li>';
html += '<li class="'+(currentPage == 1?"disabled":"")+'" data-pb-page-number="'+(currentPage==1?1:currentPage-1)+'">«</li>';
for (var i = 1; i <= lastPage; i++) {
html += '<li class="'+(currentPage == i?"active":"")+'" data-pb-page-number="'+i+'">'+ i +'</li>';
}
html += '<li class="'+(lastPage == currentPage?"disabled":"")+'" data-pb-page-number="'+(currentPage==lastPage?lastPage:currentPage+1)+'">»</li>';
html += '<li class="'+(lastPage == currentPage?"disabled":"")+'" data-pb-page-number="'+(lastPage)+'">»»</li>';
html += '</ul>';
return html;
},
each li I create it has data-pb-page-number to be used later
one more thing, how to make new requests to other pages
in the View initialize function
this.el.on('click', 'ul.pagination li:not(.disabled,.active)', this.getCustomPagesPagination);
here its implementation
getCustomPagesPagination: function (e) {
e.preventDefault();
var $el = $(e.target).closest("li");
this.reloadCustomPages({pageNumber:$el.data("pb-page-number")})
},
the the result is like this
this how I solved my problem but the question still not answered

Related

image gallery not displaying on - 1 Prev and next 4 + ( where i have applied pagination getting result from mysql database )

i am using image gallery here is the link of code image gallery -> https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_js_lightbox
the code is working fine on other page where i have not applied the pagination,
But the Problem is →
I have 4 images in gallery.
when image 1 is active OnClick << 1 PREV it doesn't show image 4
and When image 4 is active OnClick NEXT 4 >> its doesn't show any image
(But On other page where i have not applied pagination result , the image Slide is displaying properly just like this link → https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_js_lightbox )
like link Example → -3 -2 -1 <Prev 1 2 3 4 Next> 1+ 2+ .. ( Working Fine showing the image )
(pagination applied page ( Noimage -1 ) <<Prev 1 2 3 4 Next>> ( Noimage 4+ )
But When I Changed the per page result in pagination from 8 to 1 its work fine its show all image in -PREV and Next+
AND When i change the → $per_page = 8; -- To → $per_page = 1; its Work fine.
i think it is because of the [i] or [ 1 , -1 ] value in of both pagination and image slide
Can anyone pls Advice, how to solve this image No display problem
<?php
include('includes/db_msqli.php');
if (!isset($_SESSION['id'])) {
header("Location: login");
die();
}
?>
<?php
ini_set('display_errors', 1);
error_reporting(~0);
$strKeyword = null;
if(isset($_POST["txtKeyword"]))
{
$strKeyword = $_POST["txtKeyword"];
}
if(isset($_GET["txtKeyword"]))
{
$strKeyword = $_GET["txtKeyword"];
}
?>
<?php
$id=$_SESSION["id"];
$sql = "SELECT block.*, register.*
FROM block, register
WHERE block.block_by = '$id' AND register.id = block.block_to";
$query = mysqli_query($conn,$sql);
$num_rows = mysqli_num_rows($query);
$per_page = 8; **// Per Page Result to 1 **
$page = 1;
if(isset($_GET["Page"]))
{
$page = $_GET["Page"];
}
$prev_page = $page-1;
$next_page = $page+1;
$row_start = (($per_page*$page)-$per_page);
if($num_rows<=$per_page)
{
$num_pages =1;
}
else if(($num_rows % $per_page)==0)
{
$num_pages =($num_rows/$per_page) ;
}
else
{
$num_pages =($num_rows/$per_page)+1;
$num_pages = (int)$num_pages;
}
$row_end = $per_page * $page;
if($row_end > $num_rows=$per_page)
{
$row_end = $num_rows;
}
$sql .= " ORDER BY block_id DESC LIMIT $row_start ,$row_end ";
$query = mysqli_query($conn,$sql);
$recordExists = 0;
?>
<?php
while($row=mysqli_fetch_array($query,MYSQLI_ASSOC))
{
if($recordExists == 0 )
$recordExists = 1;
?>
//--- code image gallery -> https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_js_lightbox --- //
//----here is Result from mysql data base --- //
<?php
}
if($recordExists == 0 ){
echo "<div class='no_pending_int'>
<span>No blocked Member..!!</span>
</div>";
}
?>
<br>
<a class='precord'>Total Result : <?php echo $num_pages;?> Page's </a>
<br><br>
<?php
if($prev_page)
{
echo " <a class='pprev' href='$_SERVER[SCRIPT_NAME]?Page=$prev_page&txtKeyword=$strKeyword'>◄</a> ";
}
for($i = max(1, $page - 3); $i <= min($page + 3, $num_pages); $i++)
{
if($i != $page)
{
echo " <a class='numbers' href='$_SERVER[SCRIPT_NAME]?Page=$i&txtKeyword=$strKeyword'>$i</a> ";
}
else
{
echo "<b class='numberactive'>$i</b>";
}
}
if($page!=$num_pages)
{
echo " <a class='pprev' href ='$_SERVER[SCRIPT_NAME]?Page=$next_page&txtKeyword=$strKeyword'>►</a> ";
}
$conn = null;
?>

How to enable disable option value in select based on condition PHP

After user select location,in the next select option which is select car, will show list of car in selected location..The list of car retrieved direct from database..So i need to display all the car list in that area and need to disable enable the car list according the condition which is if the car id is not available the option value will disabled..and the option value become enable if car id is available..
<?php
$car = "SELECT *,location_master.location_id , location_master.location_name,
appcarinfo.loc_id_ext, appcarinfo.location ,appcarinfo.model ,appcarinfo.noplat FROM location_master
INNER JOIN appcarinfo ON
appcarinfo.lat = location_master.gmaplat
AND
appcarinfo.lon = location_master.gmaplng
where appcarinfo.model='".$fetchres['idmodel']."' ";
$qcar = mysqli_query($conn, $car);
?>
<option disabled value="" selected hidden>Please Select Car</option>
<?php
while ($showcar= mysqli_fetch_array($qcar))
{
if ($showcar['car_id']=="Available")
{
?>
<option class="<?php echo $showcar['lon']; ?>" value="<?php echo $showcar['car_id']; ?>" enabled> <?php echo $fetchres['maker'].' '.$fetchres['model_name'].'-'.$showcar['noplat'].' ' .$showcar['location_name']; ?></option>
<?php
}
else
?> <option class="<?php echo $showcar['lon']; ?>" value="<?php echo $showcar['car_id']; ?>" disabled> <?php echo $fetchres['maker'].' '.$fetchres['model_name'].'-'.$showcar['noplat'].' ' .$showcar['location_name']; ?></option>
<?php
}
?>
</select>
SELECT OPTION
I'm also new to AJAX..how to pass data and retrieve it back to select option
//check availability car
function check_availability()
{
//id from form
var reservation1 = document.getElementById("reservation");
var pickup_date = document.getElementById("pickup_date").value;
var return_date = document.getElementById("return_date").value;
var pickup_time = document.getElementById("pickup_time").value;
var return_time = document.getElementById("return_time").value;
var carID= document.getElementById("carID").value;
$.ajax({
type : "POST",
url : "function/check_car_availability.php",
data : {
pickup_date : pickup_date,
return_date : return_date,
pickup_time : pickup_time,
return_time : return_time,
carID : carID,
},
dataType : "JSON",
success : function(data) {
$('#edt_pickup').val(data.edt_pickup);
$('#edt_return').val(data.edt_return);
$('#msgCheck').html(data.msgCheck);
$('#btn_proceed').html(data.btn_proceed);
}
});
}
check_car_availability.php
<?php
if ($_POST['pickup_date'])
{
$pickup_date = $_POST['pickup_date'];
$return_date = $_POST['return_date'];
$pickup_time = $_POST['pickup_time'];
$return_time = $_POST['return_time'];
$car_id = $_POST['car_id'];
$owner_id = $_POST['owner_id'];
//convert normal date to epoch
$pickup_date1 = explode("/",$pickup_date);
$return_date1 = explode("/",$return_date);
$pickup_time1 = explode(":",$pickup_time);
$return_time1 = explode(":",$return_time);
//hour, minute, second, month, day, year
$edt_pickup = mktime($pickup_time1[0],$pickup_time1[1],0,$pickup_date1[1],$pickup_date1[0],$pickup_date1[2]);
$edt_return = mktime($return_time1[0],$return_time1[1],0,$return_date1[1],$return_date1[0],$return_date1[2]);
//convert from d/m/Y to Y-m-d
$pickup_date_2 = $pickup_date1[2]."-".$pickup_date1[1]."-".$pickup_date1[0];
$return_date_2 = $return_date1[2]."-".$return_date1[1]."-".$return_date1[0];
//keluarkan tarikh yg customer pilih ada tak dlm booking master
$chkBooked = mysqli_query($conn, "SELECT count(car_id) AS countid FROM appbooking WHERE
((start_rent >= '$edt_pickup' AND end_rent <= '$edt_return')
OR (((start_rent <= '$edt_pickup' AND end_rent >= '$edt_return')))
OR (((end_rent >= '$edt_pickup' AND end_rent <= '$edt_return')))
OR (((start_rent >= '$edt_pickup' AND start_rent <= '$edt_return')))) AND car_id = '$car_id' AND status !='0'");
$fetchBooked = mysqli_fetch_array($chkBooked);
if($fetchBooked['countid'] != 0) //kalau ada show not available
{
$availability = "Not Available";
$available_count = 0;
} else //kalau tak de show available
{
$availability = "Available";
$available_count = 1;
}
//keluarkan car details
$carDetails = mysqli_query($conn, "SELECT * FROM appcarinfo WHERE car_id = '$car_id'");
$fetchchkowner = mysqli_fetch_array($carDetails);
//kalau manual availability check ada tak date dlm range yg owner dah set
$sql = mysqli_query($conn, "SELECT count(car_availability.availability_id) AS cntAvail FROM appcarinfo INNER JOIN car_availability ON car_availability.car_id = appcarinfo.car_id WHERE appcarinfo.car_id = '$car_id' AND car_availability.start_available <= '$edt_pickup' AND car_availability.end_available >= '$edt_return'");
$fetch = mysqli_fetch_array($sql);
if ($fetchchkowner['custom_availability'] == 1) //if owner set manual availability
{
if ($fetch['cntAvail'] > 0) //kalau ada
{
$avail = 1;
} else //kalau tak de
{
$avail = 0;
}
} else //if owner set auto availability
{
$avail = 1;
}
//check if this is klezcar car
if($fetchchkowner["owner_id"] == "0")
{
$klezcar_loc_id = $fetchchkowner["loc_id_ext"];
//check availability for blocked date klezcar
$sqlBlock = "SELECT * FROM `blocked_date_klezcar` where (
('".$pickup_date_2."' > startdate and '".$pickup_date_2."' < enddate)
or ('".$return_date_2."' > startdate and '".$return_date_2."' < enddate)
or ('".$pickup_date_2."' = startdate)
or ('".$return_date_2."' = enddate)
or ('".$return_date_2."' = startdate)
or ('".$return_date_2."' = enddate)
) and (location=0 or location=".$klezcar_loc_id.") order by location desc limit 1";
$queryBlock = mysqli_query($conn,$sqlBlock);
if(mysqli_num_rows($queryBlock) > 0)
{
$resBlock = mysqli_fetch_object($queryBlock);
$avail = 0;
$klezcar_blocked = 1;
$klezcar_blocked_reason = $resBlock->reason;
}
else
{
$klezcar_blocked = 0;
}
}
//calculation price rate
include 'calculation_price/calculationprice.php';
$encry = md5($edt_pickup.$edt_return.$total_pay.$total_rate.floor($day).$bhourplus.$car_id.$owner_id.$secretAuth);
//combine appbooking & car availability variable
if ($avail == 1 && $available_count == 1)
{
$availStatus = "<div class='alert alert-success'>You are good, car available.<br>Rental Price : Total <span style='font-size:20px; font-weight: bold;'>".number_format($total_pay,2)."</span> for ".floor($day)." day(s) ".$bhourplus." hour(s)</div>";
$btn_proceed = "<a href='confirmbooking.php?pickupdate=".$edt_pickup."&returndate=".$edt_return."&totalpay=".$total_pay."&totalrate=".$total_rate."&bookday=".floor($day)."&bookhour=".$bhourplus."&carid=".$car_id."&ownerid=".$owner_id."&encry=".$encry."' class='btn btn-primary'>Proceed</a>";
} else
{
$availStatus = "<div class='alert alert-danger'>We are sorry, car not available. Please refer Available & Not available date table.</div>";
$btn_proceed = "";
if($klezcar_blocked === 1)
{
$availStatus = "<div class='alert alert-danger'>".$klezcar_blocked_reason."</div>";
$btn_proceed = "";
}
}
/* *** SPECIAL FOR RAYA 2019 *** */
$start_blocked_date = "2019-06-04";
$end_blocked_date = "2019-06-09";
if( ($pickup_date_2 >= $start_blocked_date && $pickup_date_2 <= $end_blocked_date)
|| ($return_date_2 >= $start_blocked_date && $return_date_2 <= $end_blocked_date)
|| ($pickup_date_2 == $start_blocked_date)
|| ($return_date_2 == $end_blocked_date)
|| ($return_date_2 == $start_blocked_date)
|| ($return_date_2 == $end_blocked_date))
{
$availStatus = "<div class='alert alert-danger'>The date has been marked as Hari Raya Aidlifitri holiday session. We accept minimum rental of 7 days and above only. Please re-select date at least 3/6/2019 - 10/6/2019.</div>";
$btn_proceed = "";
}
/* *** SPECIAL FOR RAYA 2019 *** */
//return value
$data['edt_pickup'] = $edt_pickup;
$data['edt_return'] = $edt_return;
$data['msgCheck'] = $availStatus;
$data['btn_proceed'] = $btn_proceed;
$data['total_rate'] = $total_rate;
$data['total_pay'] = $total_pay;
$data['no_day_booking'] = floor($day);
$data['no_hour_booking'] = $bhourplus;
echo json_encode($data);
}
?>

refresh multiple classes every n secs from php backend

I have some code in jquery that connects to php and refreshes the class with latest data. This is working ok. However, I need to update 3 classes and when it refreshses the values are empty.
Is there a way I can query db and update 3 classes with fresh data every n sec. Many thanks
js
// Update server with latest actions,destructions and return requests
setInterval(function() {
$.get('/domain/admin/refreshBox.php', function(data) {
$(".actions").text(data);
$(".retrievals").text(data);
$(".returns").text(data);
});
}, 10000);
php
$sql= mysqli_query($conn,"SELECT count(*) as total FROM act WHERE new = '1'");
$rows = mysqli_fetch_assoc($sql);
$num = $rows['total'];
//echo $num;
$ni = $num;
if($ni < 1) {
$ni = '0';
}
echo $ni;
$nisql= mysqli_query($conn,"SELECT count(*) as ni FROM act WHERE activity='New Intake' AND new = '1'");
$niintknum_row = mysqli_fetch_assoc($nisql);
$niintknum = $niintknum_row['ni'];
//echo $num;
$niintk_num = $niintknum;
if($niintk_num < 1) {
$niintk_num = '0';
echo $niintk_num;
$brtvsql= mysqli_query($conn,"SELECT count(*) as rtrv FROM act WHERE activity='Box Retrieval' AND new = '1'");
$brtv_row = mysqli_fetch_assoc($brtvsql);
$brtvnum = $brtv_row['rtrv'];
//echo $num;
$brtv_num = $brtvnum;
if($brtv_num < 1) {
$brtv_num = '0';
echo $brtv_num;
$brtnsql= mysqli_query($conn,"SELECT count(*) as brtn FROM act WHERE activity='Box Return' AND new = '1'");
$brtn_row = mysqli_fetch_assoc($brtnsql);
$brtnnum = $brtn_row['brtn'];
//echo $num;
$brtn_num = $brtnnum;
if($brtn_num < 1) {
$brtn_num = '0';
}
echo $brtn_num;

Submenu keep active when user click on it and open in a new page

I have problem when a visitor clicks on a submenu and the link opens in a new page, so I want to keep that submenu active on that page.
I have css class active and javascript for opening it, what I need is to make it with php to be active.
This is UL with class:
This is my code. Can it be done with php or with javascript.
<ul>
<?php
$qKategori = ("SELECT * FROM kategori WHERE kprind = 0");
$rKategori = mysqli_query($dbc, $qKategori);
if ($rKategori) {
while ($exKat = mysqli_fetch_array($rKategori, MYSQLI_ASSOC)){
$emrikategorise = $exKat['kemri'];
$idkategori = $exKat['kid'];
$idprind = $exKat['kprind'];
?>
<li><?=$emrikategorise;?>
<ul>
<?php
$qPrind = ("SELECT * FROM kategori WHERE kprind = '".$idkategori."'");
$rPrind = mysqli_query($dbc,$qPrind);
while($prind = mysqli_fetch_array($rPrind)) {
?>
<li><?=$prind['kemri']?> </li>
<?php
}
mysqli_free_result($rPrind);
?>
</ul>
</li>
<?php }
mysqli_free_result($rKategori);
}
?>
</ul>
You can see menu on the left in The website is www.sitimobil.mk
You probably will need to build the array before outputting to be able to determine which menus should be active. You can also combine it with an optimization of the query to not have to do 1 query per category.
Something like:
$active = isset($_GET['kid'] ? $_GET['kid'] : -1;
$tree = array();
$list = array();
$qKategori = ("SELECT * FROM kategori ORDER BY kprind");
$rKategori = mysqli_query($dbc, $qKategori);
if ($rKategori) {
while ($exKat = mysqli_fetch_array($rKategori, MYSQLI_ASSOC)){
$id = $exKat['kid'];
//To prevent numerical array with unused space
$name = 'kategori'.$exKat['kid'];
$list[$name] = $exKat;
//Calculate depth to see if the menu is a sub..sub..sub menu etc.
$parent = $list[$name]['kprind'];
if($parent == 0) {
$list[$name]['depth'] = 0;
$list[$name]['childCount'] = 0;
}
else {
$list['kategori'.$parent]['childCount']++;
$list[$name]['depth'] = $list['kategori'.$parent]['depth']+1; //Increment
}
if($id == $active) {
$list[$name]['active'] = true;
while($parent != 0) {
$parentName = 'kategori'.$parent;
$list[$parentName]['active'] = true;
$parent = $list[$parentName]['kprind'];
}
}
else
$list[$name]['active'] = false;
}
mysqli_free_result($rPrind);
//Once we have that we can output the results...
function output_menu($list, $parent = 0, $active = false)
$activeClass = $active ? ' class="active"' : '';
echo '<ul'.$activeClass.'>';
foreach($list as $row){
if($row['kprind'] != $parent) continue;
$link = $row['kprind'] == 0 ? '#' : 'kategori.php?kid='.$row['kid'];
echo '<li>'.$row['kemri'].'';
if($row['childCount'] > 0)
output_menu($list, $row['kprind'], $row['active']);
echo '</li>';
}
echo '</ul>';
}
output_menu($list);
}
This is still a bit rough but should do the trick. It can probably be optimized so that we don't have to go through the list too many times but has the benefit of not having to request too many calls to the database. That should result in a lighter workload for the DB and faster output.

javascript conflict between ajax pagination and flowplayer plug-in

I applied an ajax pagination in my web project it worked well however my flowplayer plug-in stopped working i think they are in conflict or they are overwriting each other's javascript so i ve searched for a while in web but i couldn t find the solution. ( i tried even noConflict method)
What should i do ? Can anyone help me please ?
Here is my index.php:
<?php
// This first query is just to get the total count of rows
$sql = "SELECT id_video FROM video ORDER BY id_video DESC";
$res = $connexion->query($sql);
$count=$res->rowCount();
//print_r($count);
// Here we have the total row count
//$total_rows = $row[0];
// Specify how many results per page
$rpp = 4;
// This tells us the page number of our last page
$last = ceil($count/$rpp);
// This makes sure $last cannot be less than 1
if($last < 1){
$last = 1;
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<title>Exemple</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="css/reset.css" />
<link rel="stylesheet" href="css/typocolor.css" />
<link rel="stylesheet" href="css/index_media_ie.css" />
<link rel="shortcut icon" href="image/favicon.ico" />
<link href='http://fonts.googleapis.com/css?family=Open+Sans:400,600&subset=latin,latin-ext,cyrillic-ext' rel='stylesheet' type='text/css'>
<script>
$(document).ready(function()
{
flowplayer(".player", "./flowplayer/flowplayer-3.2.16.swf",{
clip: {
autoPlay: false,
autoBuffering: false
}
});
});
</script>
<script type="text/javascript" >
var rpp = <?php echo $rpp; ?>; // results per page
var last = <?php echo $last; ?>; // last page number
function request_page(pn){
var results_box = document.getElementById("results_box");
var pagination_controls = document.getElementById("pagination_controls");
results_box.innerHTML = "loading results ...";
var hr = new XMLHttpRequest();
hr.open("POST", "pagination_parser.php", true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var dataArray = hr.responseText.split("||");
var html_output = "";
for(i = 0; i < dataArray.length - 1; i++){
var itemArray = dataArray[i].split("|");
html_output += "<li>";
html_output += "<article>";
html_output += "<h3>"+itemArray[0]+"</h3>";
html_output += "<a class=\"player\" href="+itemArray[1]+" style=\"border:1px solid #bfbfbf;display:block;width:90%;height:250px;position:relative;margin:auto;padding:5px;background-color:white;box-shadow: 0px 0px 5px rgb(204, 204, 204);\"></a>";
html_output += "<p>"+itemArray[2]+"</p>";
html_output += "</article>";
html_output += "</li>";
}
results_box.innerHTML = html_output;
}
}
hr.send("rpp="+rpp+"&last="+last+"&pn="+pn);
// Change the pagination controls
var paginationCtrls = "";
// Only if there is more than 1 page worth of results give the user pagination controls
if(last != 1){
if (pn > 1) {
paginationCtrls += '<button onclick="request_page('+(pn-1)+')"><</button>';
}
paginationCtrls += ' <b>Page '+pn+' of '+last+'</b> ';
if (pn != last) {
paginationCtrls += '<button onclick="request_page('+(pn+1)+')">></button>';
}
}
pagination_controls.innerHTML = paginationCtrls;
}
</script>
</head>
<body>
<div id="wrapper">
.
.
.
</div>
<script src="./js/jquery.js"></script>
<script src="http://cdn.jquerytools.org/1.2.7/full/jquery.tools.min.js"></script>
<!-- bxSlider Javascript file -->
<script src="./js/bxslider/jquery.bxslider.min.js"></script>
<!-- bxSlider CSS file -->
<link href="./js/bxslider/jquery.bxslider.css" rel="stylesheet" />
<script src="./flowplayer/flowplayer-3.2.12.min.js"></script>
<script src="./js/comportement.js"></script>
<script> request_page(1); </script>
</body>
</html>
and pagination_parser.php (which i found it on developphp.com)
<?php
// Make the script run only if there is a page number posted to this script
if(isset($_POST['pn'])){
$rpp = preg_replace('#[^0-9]#', '', $_POST['rpp']);
$last = preg_replace('#[^0-9]#', '', $_POST['last']);
$pn = preg_replace('#[^0-9]#', '', $_POST['pn']);
// This makes sure the page number isn't below 1, or more than our $last page
if ($pn < 1) {
$pn = 1;
} else if ($pn > $last) {
$pn = $last;
}
// Connect to our database here
include_once("bdd.php");
$connexion->exec("SET CHARACTER SET utf8");
// This sets the range of rows to query for the chosen $pn
$limit = 'LIMIT ' .($pn - 1) * $rpp .',' .$rpp;
// This is your query again, it is for grabbing just one page worth of rows by applying $limit
$sql = "SELECT * FROM video ORDER BY id_video DESC $limit";
$res = $connexion->query($sql);
//$query = mysqli_query($db_conx, $sql);
$dataString = '';
while($row = $res->fetch(PDO::FETCH_ASSOC))//mysqli_fetch_array($query, MYSQLI_ASSOC)){
{
$titre=$row['titre'];
$description=$row['description'];
$src=$row['source_video'];
//$itemdate = strftime("%b %d, %Y", strtotime($row["datemade"]));
$dataString .= $titre.'|'.$src.'|'.$description.'||';
}
// Close your database connection
//mysqli_close($db_conx);
// Echo the results back to Ajax
echo $dataString;
exit();
}
?>
Try to comment out and execute your script I think its jQuery conflicting with it.

Categories

Resources