PHP javascript refresh div breaks page with multiple timers after setInterval runs - javascript

I have a page fetching multiple data for a table. One of the data columns has a date and time value
from where a countdown timer runs.Each row has it's own countdown timer and it's working well.
However after I included javascript code to refresh the table after every 10 seconds and get new records inserted into the database, the page breaks and only displays the first timer in the countdown column timers. The tables uses datatable js library. Any recommended way that can enable the page div container to load the page correctly with javascript setinterval function will be highly appreciated.
The code below is what I use for refreshing the page div container
<script type="text/javascript">
$(document).ready(function() {
$.ajaxSetup({
cache: false
});
setInterval(function() {
var url = "loaded.php";
$('#loaded_orders').load(url + " #loaded_orders").fadeIn('slow');
}, 10000);
});
This code I use to start the count down timer in the table columns. The table is wrapped in the div with the id "loaded_orders"
<table class="table table-bordered table stripped table hover" data-order='[[ 0, " desc" ]]' id="dataTable" width="100%" cellspacing="0">
<thead>
<tr>
<th>ID </th>
<th>Order No</th>
<th>Order title</th>
<th>Actual Deadline</th>
<th>Assigned Writer</th>
<th>Inserted By</th>
<th>Action</th>
</tr>
</thead>
<tfoot>
<tr>
<th>ID </th>
<th>Order No.</th>
<th>Order title</th>
<th>Actual Deadline</th>
<th>Assigned Writer</th>
<th>Inserted By</th>
<th>Action</th>
</tr>
</tfoot>
<tbody>
<?php while ($row = $result->fetch_assoc()) {
//echo json_encode($row);
?>
<tr>
<td><?= $row['id']; ?> </td>
<td><?= $row['orderno']; ?></td>
<td> <?= $row['ordertitle']; ?> </td>
<td>
<script src="./js/countdown.js" type="text/javascript"></script>
<script>
u_d = ("d" + "<?= $row['id']; ?>");
u_h = ("h" + "<?= $row['id']; ?>");
u_m = ("m" + "<?= $row['id']; ?>");
u_s = ("s" + "<?= $row['id']; ?>");
ty = "<?= $row['actdeadline']; ?>";
document.write("<div class='writerDeadl'><p class='timer'><span id='" + u_d + "'></span> Day(s) <span id='" + u_h + "'></span>:<span id='" + u_m + "'></span>:<span id='" + u_s + "'></span></p></div>");
countdown(ty, u_d, u_h, u_m, u_s);
</script>
</td>
<td><?= $row['asswriter']; ?> </td>
<td><?= $row['inserted_by']; ?></td>
<td>Details |
del<i class="fas fa-trash "></i> |
Edit<i class="fas fa-edit"></i> |
send<i class="fas fa-paper-plane"></i> |
cancel
</td>
</tr>
<?php } ?>
</tbody>
</table>
The code below is for countdown.js file
function countdown(endDate, uid_d, uid_h, uid_m, uid_s) {
let timer, days, hours, minutes, seconds;
endDate = new Date(endDate).getTime();
if (isNaN(endDate)) {
return;
}
if (uid_d != null) {
timer = setInterval(calculate, 1000);
}
function calculate() {
let startDate = new Date();
startDate = new Date(
startDate.getUTCFullYear(),
startDate.getUTCMonth(),
startDate.getUTCDate(),
startDate.getUTCHours(),
startDate.getUTCMinutes(),
startDate.getUTCSeconds()
);
let timeRemaining = parseInt((endDate - startDate.getTime()) / 1000);
if (timeRemaining >= 0) {
days = parseInt(timeRemaining / 86400);
timeRemaining = timeRemaining % 86400;
hours = parseInt(timeRemaining / 3600);
timeRemaining = timeRemaining % 3600;
minutes = parseInt(timeRemaining / 60);
timeRemaining = timeRemaining % 60;
seconds = parseInt(timeRemaining);
document.getElementById(uid_d).innerHTML = parseInt(days, 10);
document.getElementById(uid_h).innerHTML = ("0" + hours).slice(-2);
document.getElementById(uid_m).innerHTML = ("0" + minutes).slice(-2);
document.getElementById(uid_s).innerHTML = ("0" + seconds).slice(-2);
} else {
return;
}
}
}

I discovered the only way to refresh datatables with setInterval without losing datatbles functionality is to use json data then draw the table. After ding that everything is working well.

Related

How to render a Dynamic Timer (Countdown) With JavaScript and Datatable's Render?

I want to render a Countdown for a different time for different Products I use MVC EntityFrameWork and for client-side jQuery and JavaScript.
When You datatable's render section so you find a JavaScript SetInterval function to make it dynamic but it didn't work When I only use the JavaScript method SetTime (made by self)
The SetTimer Function gets the remaining time for products and I want This function to run again and again every second to make this dynamic
Is there any other way to perform this Action?
table = $('#ProductTable').DataTable({
"ajax": {
"url": "/api/product/",
"type": "GET",
"dataSrc": ""
},
"columns": [
{
"data": "id",
render: function (data, type, Product) {
debugger;
return "<div id='ProductCover'> <div id='Product-img-div'> <img src='/Content/Images/" + Product.images + "' width='200px'></div> <div style='margin-right: 50px;'> Product Name:<h5> " + Product.productName + " <h5> Product Descrption: <h5> " + Product.description + "</h5> </div> <div class='countdown'> End Time: <span class='clock'> " + **setInterval(SetTimer(Product.endBidDate),1000)** +" </span > </div > <br><div style='margin-left:50px;'> Current Highest Amount:<h5>" + Product.highestAmount + " </h5> </div> </div> <button type='button' class='btn btn-primary' onclick='BidModal(" + Product.id + ")'>new Bids </button> <button class='btn btn-primary' data-toggle='modal' data-target='#BuyerQuyerModal' data-whatever='#mdo' onclick='Select(" + Product.id + ")'>Ask Seller</button> </div> ";
}
}
]
})
}
This Script finds the remaining time with the End Date of the Product Sale and I call this function in HTML (datatable's render section) How can I call this with SetInterval so I can time goes in backward
function setTimer(endTimes) {
var endTime = endTimes;
timerrrr = endTime
endTime = (Date.parse(endTime) / 1000);
var now = new Date();
now = (Date.parse(now) / 1000);
var timeLeft = endTime - now;
var days = Math.floor(timeLeft / 86400);
var hours = Math.floor((timeLeft - (days * 86400)) / 3600);
var minutes = Math.floor((timeLeft - (days * 86400) - (hours * 3600)) / 60);
var seconds = Math.floor((timeLeft - (days * 86400) - (hours * 3600) - (minutes * 60)));
if (hours < "10") { hours = "0" + hours; }
if (minutes < "10") { minutes = "0" + minutes; }
if (seconds < "10") { seconds = "0" + seconds; }
return `${days} : ${hours} : ${minutes} : ${seconds}`;
}
I would place the setInterval function in the DataTable initComplete option, instead of in a column renderer:
initComplete: function () {
setInterval(function () {
doCountdowns();
}, 1000);
}
Here is a very basic runnable demo showing that aproach:
function doCountdowns() {
$( '.endtime' ).each(function( index ) {
doCountdown( this ); // a td node
});
}
function doCountdown( node ) {
let endTime = Date.parse( $( node ).html() ) / 1000;
let now = (Date.parse(new Date()) / 1000);
let timeLeft = endTime - now;
let days = Math.floor(timeLeft / 86400);
let hours = Math.floor((timeLeft - (days * 86400)) / 3600);
let minutes = Math.floor((timeLeft - (days * 86400) - (hours * 3600)) / 60);
let seconds = Math.floor((timeLeft - (days * 86400) - (hours * 3600) - (minutes * 60)));
if (hours < "10") { hours = "0" + hours; }
if (minutes < "10") { minutes = "0" + minutes; }
if (seconds < "10") { seconds = "0" + seconds; }
$( node ).next("td").html( `${days} : ${hours} : ${minutes} : ${seconds}` );
}
$(document).ready(function() {
$('#example').DataTable( {
initComplete: function () {
setInterval(function () {
doCountdowns();
}, 1000);
}
} );
} );
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Demo</title>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<script src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.css">
<link rel="stylesheet" type="text/css" href="https://datatables.net/media/css/site-examples.css">
</head>
<body>
<div style="margin: 20px;">
<table id="example" class="display dataTable cell-border" style="width:100%">
<thead>
<tr>
<th>Product ID</th>
<th>End Bid Date</th>
<th>Time Remaining</th>
</tr>
</thead>
<tbody>
<tr>
<td>123</td>
<td class="endtime">2022-12-04 13:44:35</td>
<td></td>
</tr>
<tr>
<td>456</td>
<td class="endtime">2022-11-07 06:21:12</td>
<td></td>
</tr>
<tr>
<td>789</td>
<td class="endtime">2022-10-04 17:23:00</td>
<td></td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
You may need to adjust this to account for your specific data & formatting - and the fact that you are using an Ajax data source - but the approach should be the same.
As an enhancement: You may also need some logic to handle the data when the deadline is reached, otherwise you will get incorrect data displayed.

change datetime format of datatable.js from ex. (Oct 24 2017 06:08:53:000AM) to (2017-10-24 06:08:53.000)

Oct 24 2017 06:08:53:000AM - (Default output of datatable.js)
2017-10-24 06:08:53.000 - Here's what I extracted from SQL server
I want the output to be the same as what I got from SQL server
Sample Screenshot of DataTable.js output
Sample Screenshot of SQL server output
I'm using this code to call the table
<script>
$(document).ready(function(){
$('#myTable').dataTable({
});
});
</script>
</html>
But the format automatically change and I'm trying to search for some information how to change the datetime format to become the same as what I got in SQL server.
HTML CODE for datatable.js
<table id="myTable" class="table table-striped" >
<thead>
<tr>
<th>Mobile Number</th>
<th>First Name</th>
<th>Last Name</th>
<th>DateTime</th>
<th>Message</th>
</tr>
</thead>
<tbody>
<?php
$z = 0;
$x = 0;
$query_qmobile = "select distinct "
. "phone_book.s_mobile_number as 'Mobile Number', "
. "phone_book.s_first_name as 'First Name', "
. "phone_book.s_last_name as 'Last Name', "
. "inbox.dt_datetime as 'Date', "
. "inbox.s_message as 'Message' "
. "from phone_book, inbox "
. "where phone_book.s_mobile_number = inbox.s_sender "
. "order by dt_datetime DESC";
$result_qmobile = mssql_query($query_qmobile);
$numRows_qmobile = mssql_num_rows($result_qmobile); //TOTAL ROW COUNTS
$data_q4 = array();
while($row=mssql_fetch_assoc($result_qmobile)){
$data_q4[]= $row;
}
for($x;$x<$numRows_qmobile;$x++){
echo '<tr>';
echo '<td> '.$data_q4[$z]['Mobile Number'].' </td>';
echo '<td> '.$data_q4[$z]['First Name'].' </td>';
echo '<td> '.$data_q4[$z]['Last Name'].' </td>';
echo '<td> '.$data_q4[$z]['Date'].' </td>'; //THIS IS THE PART THAT CONVERT THE DATA
echo '<td> '.$data_q4[$z]['Message'].' </td>';
echo '</tr>';
$z++;
}
?>
</tbody>
</table>
This should do the trick
document.write(ConvertDate("Oct 24 2017 06:08:53:000AM"));
function ConvertDate(string){
var date = {
month : "",
day : "",
year : "",
hours : "",
minutes : "",
seconds : "",
milliseconds : "",
period : ""
};
var dateArr = string.split(" ");
var timeArr = dateArr[3].split(":");
date.month = function () {
// a dirty trick to get the numeric value
var value = new Date(dateArr[0] + " 1").getMonth()
return value < 10 ? "0" + value : value;
}();
date.day = dateArr[1];
date.year = dateArr[2];
date.hours = timeArr[0];
date.minutes = timeArr[1];
date.seconds = timeArr[2];
date.milliseconds = timeArr[3].substring(0, 3);
date.period = timeArr[3].replace(date.milliseconds, "");
return date.year+"-"+date.month+"-"+date.day+" "+(date.period == "PM" ? date.hours + 12 : date.hours)+":"+date.minutes+":"+date.seconds+"."+date.milliseconds;
}
Then form jquery
$("#myTable <some selector for your date time column>").each(function(){
$(this).html(ConvertDate($(this).html()));
});
UPDATED
-CHANGE
echo '<td> '.$data_q4[$z]['Date'].' </td>'; to
echo '<td class=\"dates\"> '.$data_q4[$z]['Date'].' </td>';
-THEN
$("#myTable .dates").each(function(){
$(this).html(ConvertDate($(this).html()));
});

Repeating jquery script in every row in table automatically

I have problem with this script. When I change value in column "TO" in table, script substract automatically in column "Number of hours" only in first row value but others no. I need application script with name "PRO1" (updateDue) in every row in table.
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<link rel="stylesheet" href="style.css">
<body onload="changeText()">
<?php
$date = date('Y-m-01');
$end = date('Y-m-t');
//, strtotime('-1 months')//
?>
<?php include 'dbconfig.php' ?>
<table border="1" id="myTable">
<tr>
<td>Date</td>
<td>From</td>
<td>To</td>
<td>Number of hours</td>
</tr>
<tr class="item">
<?php
date_default_timezone_set('UTC');
while(strtotime($date) <= strtotime($end)) {
$day_num = date('d', strtotime($date));
$day_name= date('l', strtotime($date));
$date = date("Y-m-d", strtotime("+1 day", strtotime($date)));
if (($day_name == "Saturday")||($day_name == "Sunday"))
{
echo "<td id='color'>$day_num $day_name</td><td></td><td></td><td></td></tr>";
}
else {
echo "<td>$day_num $day_name</td><td>";
$query = mysql_query("SELECT * FROM norma") or die(mysql_error());
while($query_row = mysql_fetch_assoc ($query))
{
$starter= $query_row['start'];
echo "<input type='text' class='txtCal' id='num1' onchange='updateDue()' value=".$query_row['start'].">";
}
echo "</td><td>";
$query = mysql_query("SELECT * FROM norma") or die(mysql_error());
while($query_row = mysql_fetch_assoc ($query))
{
$finisher= $query_row['end'];
echo "<input type='text' class='txtCal' id='num2' onchange='updateDue()' value=".$query_row['end'].">";
}
echo "</td><td>";
$ts1 = strtotime($starter);
$ts2 = strtotime($finisher);
$seconds_diff = $ts2 - $ts1;
$time = ($seconds_diff/3600);
echo "<input type='text' class='txtCal2' id='remainingval' value=".number_format((float)$time, 2, '.', '').">";
echo "</td></tr>";
}
}
?>
</tr>
<tr>
<td></td>
<td></td>
<td>Sum:</td>
<td id="total_sum_value"><span id="total_sum_value"></span></td>
</tr>
</table>
<br>
<!-- SCRIPT NAME PRO1 -->
<script>
function updateDue() {
$('#myTable tr').each(function(){
var total = parseFloat(document.getElementById("num2").value);
var val2 = parseFloat(document.getElementById("num1").value);
// to make sure that they are numbers
if (!total) { total = 0; }
if (!val2) { val2 = 0; }
var ansD = document.getElementById("remainingval");
ansD.value = total - val2;
});
}
</script>
<script>
$(document).ready(function changeText(){
$(document).ready(function changeText(){
var calculated_total_sum = 0;
$("#myTable .txtCal2").each(function () {
var get_textbox_value = $(this).val();
calculated_total_sum += parseFloat(get_textbox_value);
});
$("#total_sum_value").html(calculated_total_sum);
});
$("#myTable").on('change','input', '.txtCal2', function () {
var calculated_total_sum = 0;
$("#myTable .txtCal2").each(function () {
var get_textbox_value = $(this).val();
if ($.isNumeric(get_textbox_value)) {
calculated_total_sum += parseFloat(get_textbox_value);
}
});
$("#total_sum_value").html(calculated_total_sum);
});
});
</script>
I want dynamically change table. In column "FROM" and "TO" is value from database. This automatically subtract value (TO-FROM) and sum from this value is down. But when user change some value in column "FROM" or "TO", number will be count automatically. Thank you so much for every advice.
That's because you use the same ID for multiples TDs. You can't do that as an ID is supposed to be used once and help to identify a resource.
instead of an ID, you could use a class :
<table>
...
<tr>
<td><input type="text" class="txtCal num1" value="5" /></td>
<td><input type="text" class="txtCal num2" value="10" /></td>
<td><input type="text" class="txtCal2 remainingval" value="...">
</tr>
...
</table>
Then with jQuery, you can have access to your row values like this :
$('#myTable tr').each(function(){
var total = parseFloat($(this).find('.num2').val());
var val2 = parseFloat($(this).find('.num1').val());
...
var ansD = $(this).find(".remainingval");
ansD.val(total - val2);
});
Also let me point that mysql functions are deprecated and you should not use them anymore. Use PDO instead. (See Why shouldn't I use mysql_* functions in PHP?)

insert dropdown field from mysql using jquery

hi i have a page of invoice where i can add rows using jquery. i am able to add plain text box from .js file but i want to add a drop down menu insted of textbox. justlike default row in php page.
my page code is
<?php
$con = mysql_connect("localhost","root","");
$db = mysql_select_db("inventory_erp",$con);
$getitem=mysql_query("SELECT * FROM 0_stock_master ORDER BY stock_id ASC");
$item = '';
while($row = mysql_fetch_assoc($getitem))
{
$item .= '<option value = "'.$row['id'].'">'.$row['stock_id'].'</option>';
}
$getdescription=mysql_query("SELECT * FROM 0_stock_master ");
$description = '';
while($row2 = mysql_fetch_assoc($getdescription))
{
$description .= '<option value = "'.$row2['description'].'">'.$row2['description'].'</option>';
}
?>
<!DOCTYPE html>
<!-- saved from url=(0047)http://css-tricks.com/examples/EditableInvoice/ -->
<html lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="UTF-8">
<title>Editable Invoice</title>
<script src="./Editable Invoice_files/jquery-1.3.2.min.js"></script>
<script src="./Editable Invoice_files/example.js"></script>
</head>
</html>
<table id="items">
<tbody><tr>
<th>Item</th>
<th>Description</th>
<th>Unit Cost</th>
<th>Quantity</th>
<th>Price</th>
</tr>
<tr class="item-row">
<td class="item-name"><div class="delete-wpr"><select name="age"> <?php echo $item; ?> </select><a class="delete" href="javascript:;" title="Remove row">X</a></div></td>
<td class="description"><select name="age"> <?php echo $description; ?> </select></td>
<td><textarea class="cost">$0.00</textarea></td>
<td><textarea class="qty">1</textarea></td>
<td><span class="price">$0.00</span></td>
</tr>
<tr id="hiderow">
<td colspan="5"><a id="addrow" href="javascript:;" title="Add a row">Add a row</a></td>
</tr>
<tr>
<td colspan="2" class="blank"> </td>
<td colspan="2" class="total-line">Subtotal</td>
<td class="total-value"><div id="subtotal">$0.00</div></td>
</tr>
<tr>
<td colspan="2" class="blank"> </td>
<td colspan="2" class="total-line">Total</td>
<td class="total-value"><div id="total">$0.00</div></td>
</tr>
<tr>
<td colspan="2" class="blank"> </td>
<td colspan="2" class="total-line">Amount Paid</td>
<td class="total-value"><textarea id="paid">$0.00</textarea></td>
</tr>
<tr>
<td colspan="2" class="blank"> </td>
<td colspan="2" class="total-line balance">Balance Due</td>
<td class="total-value balance"><div class="due">$0.00</div></td>
</tr>
</tbody></table>
i am using a example.js file to add rows dynamically.
example.js
function print_today() {
// ***********************************************
// AUTHOR: WWW.CGISCRIPT.NET, LLC
// URL: http://www.cgiscript.net
// Use the script, just leave this message intact.
// Download your FREE CGI/Perl Scripts today!
// ( http://www.cgiscript.net/scripts.htm )
// ***********************************************
var now = new Date();
var months = new Array('January','February','March','April','May','June','July','August','September','October','November','December');
var date = ((now.getDate()<10) ? "0" : "")+ now.getDate();
function fourdigits(number) {
return (number < 1000) ? number + 1900 : number;
}
var today = months[now.getMonth()] + " " + date + ", " + (fourdigits(now.getYear()));
return today;
}
// from http://www.mediacollege.com/internet/javascript/number/round.html
function roundNumber(number,decimals) {
var newString;// The new rounded number
decimals = Number(decimals);
if (decimals < 1) {
newString = (Math.round(number)).toString();
} else {
var numString = number.toString();
if (numString.lastIndexOf(".") == -1) {// If there is no decimal point
numString += ".";// give it one at the end
}
var cutoff = numString.lastIndexOf(".") + decimals;// The point at which to truncate the number
var d1 = Number(numString.substring(cutoff,cutoff+1));// The value of the last decimal place that we'll end up with
var d2 = Number(numString.substring(cutoff+1,cutoff+2));// The next decimal, after the last one we want
if (d2 >= 5) {// Do we need to round up at all? If not, the string will just be truncated
if (d1 == 9 && cutoff > 0) {// If the last digit is 9, find a new cutoff point
while (cutoff > 0 && (d1 == 9 || isNaN(d1))) {
if (d1 != ".") {
cutoff -= 1;
d1 = Number(numString.substring(cutoff,cutoff+1));
} else {
cutoff -= 1;
}
}
}
d1 += 1;
}
if (d1 == 10) {
numString = numString.substring(0, numString.lastIndexOf("."));
var roundedNum = Number(numString) + 1;
newString = roundedNum.toString() + '.';
} else {
newString = numString.substring(0,cutoff) + d1.toString();
}
}
if (newString.lastIndexOf(".") == -1) {// Do this again, to the new string
newString += ".";
}
var decs = (newString.substring(newString.lastIndexOf(".")+1)).length;
for(var i=0;i<decimals-decs;i++) newString += "0";
//var newNumber = Number(newString);// make it a number if you like
return newString; // Output the result to the form field (change for your purposes)
}
function update_total() {
var total = 0;
$('.price').each(function(i){
price = $(this).html().replace("$","");
if (!isNaN(price)) total += Number(price);
});
total = roundNumber(total,2);
$('#subtotal').html("$"+total);
$('#total').html("$"+total);
update_balance();
}
function update_balance() {
var due = $("#total").html().replace("$","") - $("#paid").val().replace("$","");
due = roundNumber(due,2);
$('.due').html("$"+due);
}
function update_price() {
var row = $(this).parents('.item-row');
var price = row.find('.cost').val().replace("$","") * row.find('.qty').val();
price = roundNumber(price,2);
isNaN(price) ? row.find('.price').html("N/A") : row.find('.price').html("$"+price);
update_total();
}
function bind() {
$(".cost").blur(update_price);
$(".qty").blur(update_price);
}
$(document).ready(function() {
$('input').click(function(){
$(this).select();
});
$("#paid").blur(update_balance);
$("#addrow").click(function(){
$(".item-row:last").after('<tr class="item-row"><td class="item-name"><div class="delete-wpr"><select name="age"> <?php echo $option; ?> </select><a class="delete" href="javascript:;" title="Remove row">X</a></div></td><td class="description"><textarea>Description</textarea></td><td><textarea class="cost">$0</textarea></td><td><textarea class="qty">0</textarea></td><td><span class="price">$0</span></td></tr>');
if ($(".delete").length > 0) $(".delete").show();
bind();
});
bind();
$(".delete").live('click',function(){
$(this).parents('.item-row').remove();
update_total();
if ($(".delete").length < 2) $(".delete").hide();
});
$("#cancel-logo").click(function(){
$("#logo").removeClass('edit');
});
$("#delete-logo").click(function(){
$("#logo").remove();
});
$("#change-logo").click(function(){
$("#logo").addClass('edit');
$("#imageloc").val($("#image").attr('src'));
$("#image").select();
});
$("#save-logo").click(function(){
$("#image").attr('src',$("#imageloc").val());
$("#logo").removeClass('edit');
});
$("#date").val(print_today());
});
i am using this code in exampe.js file to add text box (Description) in new row. but i want a drop down menu from mysql database.

Pagination with help from Javascript

Community, I currently have some pagination on my page to help users page through logged tickets. To help with this, I have two table cells with Next and Previous in each respectively. Right now, when a user clicks either, it adds +1 or -1 to a JS counter that AJAX's a string. Then, I have my pagination that either goes to the next or previous 15 items in my mysql database. I wrote my JS so that if the counter is less than 1 it will go back to one. That way they dont have to repeatedly click the next button to view tickets. I'm trying to figure out a way to do that from the other end, where if the end of the result list is blank, or no more results are available, it will stay at the last counter.
PhP including initial table setup and string variable
include 'Search_Var.php'; //This file is used to build $sequel.
//$sequel is a string built by user selected search options
echo '<div style="display: none" id="Search_Var">'.$sequel.'</div>
<div class="container" style="clear: both;">
<fieldset>
<legend class="legend1"><h2> &nbsp Results &nbsp </h2></legend>
<div style="padding-top: 5px;">
<span id="page">';
include 'Search_Tickets.php'; // This file builds a table to show the first 15 results
// It also displays the total number of tickets found
// in the database matching the search query
echo '</span>';
if($openTicketsCount!=0) {include '********/***********/PreviousNext.inc.php';};
//If no tickets are available the Previous and Next boxes won't appear.
</fieldset>
</div>
</div>
';
Javascript
var count = 1;
$(window).on('load', function() {
var id = document.getElementById( "Search_Var" ).innerText;
$('.page').on('click', function() {
var page = $(this).html();
if(page == "Next")
{
count = count + 1;
}
if(page == "Previous")
{
count = count - 1;
}
if(count < 1)
{
count = 1;
}
$.get("/*******/********/Search_Pagination.inc.php?count_id=" + count + "&search_id=" + id, function(data) {
$('#page').html(data);
});
});
});
Finally, the pagination
$start = 0;
$per_page = 15;
$page = $_GET['selection_id'];
$_SESSION['role_id'] = $_GET['role_id'];
$_SESSION['bus_id'] = $_GET['bus_id'];
$_SESSION['dept_id'] = $_GET['dept_id'];
if($page <= 1)
{
$start = 0;
}
else
{
$start = $page * $per_page - $per_page;
}
$get_openTickets = $search;
$openTicketsCount = mysql_num_rows(mysql_query($get_openTickets));
$num_rows = mysql_num_rows(mysql_query($get_openTickets));
$num_pages = $num_rows / $per_page;
$get_openTickets .= " LIMIT $start, $per_page";
if($openTicketsCount !=true)
{
echo '
<td colspan = "9">No open tickets were found!</td>
';
}
else
{
$result = mysql_query($get_openTickets);
echo '
<table class="openTickets" width="1150px" border="0px" padding="0px">
<tr>
<th scope="col">ID</th>
<th scope="col" style="width:75px;">PRIORITY</th>
<th scope="col">CALLER /<br />DEPARTMENT</th>
<th scope="col">COMPANY NAME /<br />SALES REP</th>
<th scope="col" style="width:75px;">CREATED<br />ON</th>
<th scope="col" style="width:75px;">LAST<br />UPDATED</th>
<th scope="col" style="width:75px;">SOURCE</th>
<th scope="col">USER</th>
<th scope="col">CATEGORY /<br />SUBCATEGORY</th>
</tr>
';
while(($openTicket = mysql_fetch_assoc($result)))
{
echo'
<tr>
<td>'.$openTicket['call_id'].'</td>
<td style="width:75px;">'.$openTicket['priority_name'].'</td
<td>'.$openTicket['caller_name'].'<br />'.$openTicket['caller_dept'].'</td>
<td>'.$openTicket['cust_name'].'<br />'.$openTicket['cust_rep'].'</td>
<td style="width:75px;">'.$openTicket['created_on'].'</td>
<td style="width:75px;">'.$openTicket['updated_on'].'</td>
<td style="width:75px;">'.$openTicket['source_name'].'</td>
<td>'.$openTicket['created_by'].'</td>
<td>'.$openTicket['cat_name'].'<br />'.$openTicket['subcat_name'].'</td>
</tr>';
}
echo '
<tr>
<th colspan="9" style="text-align:right;">Total Open Ticket(s): '.$openTicketsCount.' </th>
</tr>
</table>';
}
have a look below
$start = 0;
$per_page = 15;
$page = $_GET['selection_id'];
$_SESSION['role_id'] = $_GET['role_id'];
$_SESSION['bus_id'] = $_GET['bus_id'];
$_SESSION['dept_id'] = $_GET['dept_id'];
if($page <= 1)
{
$start = 0;
}
else
{
$start = $page * $per_page - $per_page;
}
$get_openTickets = $search;
$openTicketsCount = mysql_num_rows(mysql_query($get_openTickets));
$num_rows = mysql_num_rows(mysql_query($get_openTickets));
$num_pages = $num_rows / $per_page;
$get_openTickets .= " LIMIT $start, $per_page";
if($openTicketsCount !=true)
{
echo '
<td colspan = "9">No open tickets were found!</td>
';
}
else
{
$result = mysql_query($get_openTickets);
echo '<input type="hidden" value="'.$num_pages.'" id="pageCount"/>
<table class="openTickets" width="1150px" border="0px" padding="0px">
<tr>
<th scope="col">ID</th>
<th scope="col" style="width:75px;">PRIORITY</th>
<th scope="col">CALLER /<br />DEPARTMENT</th>
<th scope="col">COMPANY NAME /<br />SALES REP</th>
<th scope="col" style="width:75px;">CREATED<br />ON</th>
<th scope="col" style="width:75px;">LAST<br />UPDATED</th>
<th scope="col" style="width:75px;">SOURCE</th>
<th scope="col">USER</th>
<th scope="col">CATEGORY /<br />SUBCATEGORY</th>
</tr>
';
while(($openTicket = mysql_fetch_assoc($result)))
{
echo'
<tr>
<td>'.$openTicket['call_id'].'</td>
<td style="width:75px;">'.$openTicket['priority_name'].'</td
<td>'.$openTicket['caller_name'].'<br />'.$openTicket['caller_dept'].'</td>
<td>'.$openTicket['cust_name'].'<br />'.$openTicket['cust_rep'].'</td>
<td style="width:75px;">'.$openTicket['created_on'].'</td>
<td style="width:75px;">'.$openTicket['updated_on'].'</td>
<td style="width:75px;">'.$openTicket['source_name'].'</td>
<td>'.$openTicket['created_by'].'</td>
<td>'.$openTicket['cat_name'].'<br />'.$openTicket['subcat_name'].'</td>
</tr>';
}
echo '
<tr>
<th colspan="9" style="text-align:right;">Total Open Ticket(s): '.$openTicketsCount.' </th>
</tr>
</table>';
}
And then change this
var count = 1;
$(window).on('load', function() {
var id = document.getElementById( "Search_Var" ).innerText;
$('.page').on('click', function() {
var page = $(this).html();
if(page == "Next")
{
count = count + 1;
}
if(page == "Previous")
{
count = count - 1;
}
if(count < 1)
{
count = 1;
}
if(count > parseInt( $("#pageCount").val()))
{
count = parseInt($("#pageCount").val());
}
$.get("/*******/********/Search_Pagination.inc.php?count_id=" + count + "&search_id=" + id, function(data) {
$('#page').html(data);
});
});
});
Edit:
It might be that the page count is not an integer so just check that the page count returns a valid integer, also added parseInt, it might be the reason why it was not working
I dont know why "Add Comment" is not shown for me,
But I wanted to say dont use functions mysql_*
Try using something like PDO

Categories

Resources