Can this pagination task be accomplished without the use of backgrid?

I have been exploring ways to implement server-side pagination similar to what Datatables offers, and during my search I came across the backbone.paginator library on GitHub. However, I am curious if there are any other options available as well.

After examining their examples, I noticed that they utilized another library called backgrid.js to assist with this task, along with its paginator plugin. You can find more information about both backgrid.js and its paginator plugin here.

I wonder if it's possible to achieve server-side pagination without using Backgrid? If anyone has an alternative approach or example to share, please do so.

Answer №1

Here is a JS/php code snippet I've put together for server-side pagination that you can tweak to suit your requirements and potentially refine further later on.

To begin, establish a connection with the database and create a table specifically for pagination:

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 NUL
)

Next, insert 400 identical 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, create a file named 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>

In addition, create a file named js.js:

window.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);
}

// More JavaScript functions here...

Create another file named testa.php:

<?php
$pag = "SELECT * FROM pagination ORDER BY id ASC ";
$exc = $mysqli->query($pag);
$numrows = mysqli_num_rows($exc);

// Additional PHP logic for pagination goes here...
?>

I hope this code provides some assistance to you.

Answer №2

I successfully completed the task

within the View initialize function

Triggering the necessary action

this.reloadCustomPages();

Below is the code for its implementation

reloadCustomPages: function(options) {
    var self = this;
    self.block();
    self.customPages.fetch({data: $.param(options)}).always(function () {
        self.unblock();
    });
}

In the backend (using Java Spring), I made changes to the API to accommodate new query strings

@RequestParam(value = "pageNumber", defaultValue = "1"),
@RequestParam(value = "perPage", defaultValue = "10")

Instead of directly returning the list, it now includes pagination information like

  • Total number of items in the database
  • Current page number
  • Page size
  • And the items themselves

Here's a snippet from the server-side code for reference:

@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 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 object
}

The function call instructs the server to fetch page 1 with a page size of 10

In my template, I have included this piece of code

<div class="pagination clear" style="text-align: center;">
    <%= customPages.paginationHtml %>
</div>

This is how I populate it

customPages.paginationHtml = this.generatePagination(customPages);

Here's the crucial 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"><a href="#" class="first">&laquo;&laquo;</a></li>';
    html += '<li class="'+(currentPage == 1?"disabled":"")+'" data-pb-page-number="'+(currentPage==1?1:currentPage-1)+'"><a href="#" class="prev">&laquo;</a></li>';


    for (var i = 1; i <= lastPage; i++) {
         html += '<li class="'+(currentPage == i?"active":"")+'" data-pb-page-number="'+i+'"><a href="#" class="page">'+ i +'</a></li>';
    }

    html += '<li class="'+(lastPage == currentPage?"disabled":"")+'" data-pb-page-number="'+(currentPage==lastPage?lastPage:currentPage+1)+'"><a href="#" class="next">&raquo;</a></li>';
    html += '<li class="'+(lastPage == currentPage?"disabled":"")+'" data-pb-page-number="'+(lastPage)+'"><a href="#" class="last">&raquo;&raquo;</a></li>';

    html += '</ul>';
    return html;
},

Each list item has a data-pb-page-number attribute for later use

To make requests to other pages:

Within the View initialize function

this.el.on('click', 'ul.pagination li:not(.disabled,.active)', this.getCustomPagesPagination);

Here's the code for its implementation

getCustomPagesPagination: function (e) {
    e.preventDefault();
    var $el = $(e.target).closest("li");
    this.reloadCustomPages({pageNumber:$el.data("pb-page-number")})
},

The resulting layout will resemble this:

https://i.sstatic.net/2hsJ6.png

This explains how I resolved my issue, although the initial question remains unanswered

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error message "$injector:unpr" occurs in the run method of AngularJS after minification process

I've encountered an issue with angular-xeditable on my Angular app. While it functions properly in the development environment, I'm facing an error in production when all JS files are minified: Uncaught Error: [$injector:strictdi] http://errors. ...

Is there a way to streamline this query code that seems overly complex?

Could someone please assist me in simplifying this code? I am trying to shorten or simplify the query code by using a stored procedure, but I still need to include the details inside the "()" parentheses. I am new to Node.js and would appreciate any help. ...

Visual traceroute, like the one on "yougetsignal.com", provides a way to update a div element either on demand or periodically

This is my very first question on a forum, yay! I will do my best to ask clearly and concisely. I am currently working on creating a visual traceroute similar to the one found on yougetsignal.com by Kirk Ouimet. My project is up and running using bash co ...

What is the best way to reference an ImageButton using jquery?

I created an HTML page with a special div in the body that contains a collection of buttons and images. <div id="div_one"> <button id="button_one"> <asp:Image id="image_button_one" ImageUrl=".." runat="server"> </button> </div& ...

Improving the efficiency of checking roles in Discord.js

Currently in the process of developing a Discord verification bot which includes the functionality of verifying if a user has at least one role from each required category, and then generating a summary of their roles. The existing solution I have works ...

How to disable the underline styling for autocomplete in a React Material UI component

Seeking assistance with removing underline styling and changing text color upon focus within the autocomplete component of React Material UI. Struggling to locate the specific style needing modification. Appreciate any help in advance! ...

Can you provide a step-by-step guide on creating a JSONP Ajax request using only vanilla

// Performing an ajax request in jQuery $.ajax( { url : '', data: {}, dataType:'jsonp', jsonpCallback: 'callbackName', type: 'post' ,success:function (data) { console.log('ok'); }, ...

Adding a React function to an external object without using React

Here's a simple issue that I'm facing. I am using React Highcharts Official and I want to import graphOptions from another file for the options attribute on ReactHighcharts. <ReactHighcharts highcharts={Highcharts} options={graphOptions} /> ...

How can we simplify this React component to reduce its verbosity?

After creating a test project to delve into react, react-router and react-redux, I revisited the Settings.jsx file. Now, I am pondering on how to streamline it and reduce potential errors. import React, { Component } from "react"; import { connect } from ...

Text that disappears upon clicking on show/hide按钮

Could someone please help me figure out how to prevent the "See more" text from disappearing when clicked in the example below? I want it to stay visible. Thank you! ...

Apologies, the system encountered an issue while trying to access the "name" property which was undefined. Fortunately, after refreshing the page, the error was successfully resolved

When the profile route is accessed, the code below is executed: import React, { useState, useEffect } from 'react' import { Row, Col, Form, Button } from 'react-bootstrap' import { useDispatch, useSelector } from 'react-redux' ...

Searching for a specific word within a given string using a loop

Currently, I'm developing a 'for' loop to search for my name, Andrew, in a given text and store the occurrences in an array. However, there seems to be an issue with the implementation. /*jshint multistr:true */ var text = ("Andrew is real ...

How can I create a table using a loop and an onclick function for each <td>?

I have written code to create a table in PHP using a loop. I want to add an onclick function to each cell so that when a particular cell is clicked, the background color changes. However, I am encountering an error. Am I doing something wrong? <head& ...

Looking to update the key name in a script that produces a list sorted in ascending order

I have been working on code that iterates through a flat json document and organizes the items into a hierarchical structure based on their level and position. Everything is functioning correctly, but I now need to change the name of the child elements to ...

Why is the last move of the previous player not displayed in this game of tic tac toe?

Why does the last move of the previous player not show up in this tic-tac-toe game? When it's the final turn, the square remains empty with neither an "O" nor an "X". What could be causing this issue? Here is the code snippet: The HTML code: <div ...

The toISOString() method is deducting a day from the specified value

One date format in question is as follows: Tue Oct 20 2020 00:00:00 GMT+0100 (Central European Standard Time) After using the method myValue.toISOString();, the resulting date is: 2020-10-19T23:00:00.000Z This output shows a subtraction of one day from ...

Exploring AngularJS's Unique Features: Isolated Scope and Controller Connection

Currently, I am diving into Angular and endeavoring to develop a Phone Message Log application utilizing directives. The concept is simple - the user inputs a message, clicks a button, and it gets displayed in a "Message" log below. The challenge I'm ...

Angular JS | Sending information to two separate controllers when clicked

I have a series of projects displayed in divs using ng-repeat. Each div contains a link with the project's id. My goal is to bind the project id on ng-click to update a factory. This will enable me to share the clicked project's id with another ...

Button component in React remains visible until interacted with

https://i.stack.imgur.com/gTKzT.png I'm dealing with a sign out component in my app that requires me to click on it specifically to unselect any part of the application. This is implemented using React Material UI. <MenuItem onClick={e => this ...

Internet Explorer failing to trigger Ajax requests

I'm encountering an issue with my script on my webpage - it works perfectly in Chrome, but Internet Explorer is not entering the success{} function of Ajax. It does go into the Complete{} function without any problems. I attempted to pass the data var ...