Home » Php » javascript – How to create AJAX pagination without a database?

javascript – How to create AJAX pagination without a database?

Posted by: admin July 12, 2020 Leave a comment

Questions:

Is it possible to fetch pages for AJAX pagination without the help of MySQL? Can’t I just add a PHP file with the text and markup I need to have displayed and by clicking page numbers serve that content to the user? So can this be achieved with pure jQuery and PHP? What code approach would you do to keep things simple, I mean I have 3 walls of text I need to add to my site but adding them at once on the page would confuse the users. So I decided to find a way and keep only one of them at a time based on the user’s decision. A code example would be great!

EDIT:
Should the PHP code look something like this?

<?php
    htmlspecialchars($_GET["page_number"]);
    if ($page_number == 1)
    {
        $text = var_export($text1, true);
    }

    if ($page_numer == 2)
    {
        $text = var_export($text2, true);
    }

    if ($page_number == 3)
    {
        $text = var_export($text3, true);
    }

    $text1 = 'some looong text...';
    $text2 = 'another wall of text';
    $text3 = 'and yet another one';
?>
How to&Answers:

Yes you can. You have to follow pagination rules here. You will need to pass the page number and limit of records in url.

www.example.com/index.php?page=1&limit=10

Now you create a text or php file and export all data there using var_export to return array or some other way you like.

Now you have to get page number and the trick goes here.

The array you got from text file should be divided in by limit.

$rows = array_chunk($array,$_GET['limit']);

Your result for page = $n is here.
$result = $row[$_GET['page']]

here is my index.php file.

<?php
$array = include_once('data.php');
$page = $_GET['page'] ? $_GET['page'] : 0;
$limit = $_GET['limit'];
$rows = array_chunk($array,$limit);
$result = $rows[$page];
?>
<table>
    <tr>
        <th>Id</th>
        <th>Name</th>
        <th>Desc</th>
        <th>Status</th>
    </tr>
    <?php
        foreach ($result as $res) {
    ?>
        <tr>
            <td><?php echo $res['id'] ?></td>
            <td><?php echo $res['name'] ?></td>
            <td><?php echo $res['desc'] ?></td>
            <td><?php echo $res['status'] ?></td>
        </tr>
    <?php
        }
    ?>
    <tr>
        <td colspan="2">
            <?php
                if($page>0)
                {
            ?>
            <a href="index.php?limit=<?php echo $limit; ?>&page=<?php echo ($page-1); ?>">Previous</a>
            <?php
                }
            ?>
        </td>
        <td colspan="2">
        <?php
            if (isset($rows[$page+1]))
            {
        ?>
            <a href="index.php?limit=<?php echo $limit; ?>&page=<?php echo ($page+1); ?>">Next</a>
        <?php
            }
        ?>
        </td>
    </tr>
</table>

And here is the data.php file. i have used the array to return the value.

    <?php
return
$array = [
    [
        'id' => 1,
        'name' => 'A',
        'desc' => 'Test',
        'status' => 'Active'
    ],
    [
        'id' => 2,
        'name' => 'B',
        'desc' => 'Test',
        'status' => 'Active'
    ],
    [
        'id' => 3,
        'name' => 'C',
        'desc' => 'Test',
        'status' => 'Active'
    ],
    [
        'id' => 4,
        'name' => 'D',
        'desc' => 'Test',
        'status' => 'Active'
    ],
    [
        'id' => 5,
        'name' => 'E',
        'desc' => 'Test',
        'status' => 'Active'
    ],
    [
        'id' => 6,
        'name' => 'F',
        'desc' => 'Test',
        'status' => 'Active'
    ],
];

Answer:

May be like this?

HTML+JS:

<body>
<div id="text">

</div>
<ul id="pager">
    <li><a href="#0" class="active">1</a></li>
    <li><a href="#1">2</a></li>
    <li><a href="#2">3</a></li>
</ul>
<script type="text/javascript" src="//code.jquery.com/jquery-1.11.0.js"></script>
    <script type="text/javascript">
        jQuery(document).ready(function () {
            var pager = jQuery('#pager'),/* get pager list*/
                    currentInd = pager.find('.active').attr('href').replace('#', ''), /* get active element*/
                    text = jQuery('#text'); /* Text wrapper */
/* Get first text by Ajax*/
            jQuery.ajax({
                method: 'POST',
                url: '/index.php',
                data: {
                    page: currentInd
                }
            }).done(function (data) {
                text.text(data);
            });
        });

/** On pager link click */
        jQuery(document).on('click', '#pager a', function (e) {
            e.preventDefault(); 
            var ind = jQuery(this).attr('href').replace('#', ''),/* take number */
                    text=jQuery('#text'); /* text wrapper */
/* if this link is not active then send ajax request */
            if (!jQuery(this).hasClass('active')) {
                jQuery.ajax({
                    method: 'POST',
                    url: '/index.php',
                    data: {
                        page: ind
                    }
                }).done(function (data) {
                    jQuery('#pager').find('.active').removeClass('active');
                    jQuery(this).addClass('active');
                    text.text(data);
                });
            }
        });
    </script>
    </body>

php:

<?php
$texts = array(
    'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Deserunt aperiam quis eaque ullam reprehenderit eveniet incidunt error nisi a earum voluptatem consequuntur magnam atque. Quis ipsa quo tempora libero consequuntur cumque perferendis quos atque ipsam nisi maiores ad sit iusto sequi voluptates eos neque aut asperiores ut nihil est at enim. Doloribus similique quae blanditiis provident soluta temporibus dolores libero obcaecati rerum distinctio recusandae molestiae perspiciatis dolorum quam magnam ex atque quidem exercitationem totam non sapiente magni amet delectus sequi quos at enim laborum fuga excepturi! Blanditiis illo modi harum voluptates provident hic libero explicabo culpa repellat distinctio molestias tempora obcaecati fuga. Omnis illum aliquam id nihil neque veniam laborum accusamus quidem odit porro nostrum distinctio ipsa atque quisquam natus sit excepturi at eius pariatur voluptates aspernatur nemo ipsam iure iusto ea minus tempora quod voluptate a doloremque mollitia dolorem suscipit blanditiis. Expedita itaque quibusdam magnam quod perspiciatis suscipit? ?',
    'Impedit laborum quis accusamus recusandae perferendis a optio neque tempora dolorem cum. Unde nihil nesciunt minima dicta ut sequi est hic voluptatem error totam rerum sit impedit magnam dolores earum quasi architecto dolorum accusamus ad nemo blanditiis fugiat eveniet eligendi quas ipsum aperiam vitae ducimus inventore quidem officia corporis consequatur minus excepturi. Facere a nihil tempore tempora adipisci aperiam itaque delectus sint libero quisquam rerum tenetur eaque repellat pariatur nobis commodi labore et dignissimos impedit similique saepe illo quae cum quasi repellendus iusto recusandae vel eos rem doloremque atque aliquid dolores ab vitae architecto esse quos? Veniam odio aliquam atque iusto vel laudantium tenetur inventore eius ad earum ex minima nulla nesciunt nam aspernatur nihil facilis doloribus neque rerum reiciendis at minus non veritatis cumque molestiae qui natus excepturi! Unde aliquid corrupti optio minus itaque deleniti architecto similique molestiae mollitia nobis. Saepe ullam commodi nisi doloremque tenetur officiis officia asperiores quaerat minima amet consequuntur est totam eligendi. Laudantium voluptate impedit reiciendis fugit?',
    'Aut inventore consequuntur fugit adipisci optio amet corporis voluptate tenetur quo et. Sunt repellendus sit voluptate quas sequi cupiditate veniam dignissimos nisi rerum deleniti molestias error veritatis soluta? Similique voluptatibus aperiam vitae ipsa omnis modi unde rerum odio saepe possimus voluptas illum odit vel cupiditate nam totam labore id ratione mollitia accusantium quidem repellat beatae placeat animi dolorum aut minima quos dolor iure sapiente praesentium asperiores cum pariatur sit earum eos sint deserunt commodi nobis tenetur aliquam reiciendis assumenda harum a voluptatum consequuntur. '
);
if (isset($_POST['page']) && isset($texts[$_POST['page']])) {
    echo $texts[$_POST['page']];
} else {
    echo $texts[0];
}
?>

Note: this is very simple example