1

I am implementing the following pagination example in ajax: How to display the page with ajax?

But every time I click on the following buttons or numbers on the page, it inserts the header and footer of the HTML page, that is, it is as if it inserted the whole page when receiving a response in ajax

$(function() {
    $('#amount_show').change(function(evt) {
        evt.preventDefault()
        url = $(this).parent().attr('action')
        ajaxLoad(url)
    });

    $('.data-table-pagination').on('click', '.pagination li a', function(evt) {
        evt.preventDefault()
        url = $(this).attr('data-target')
        ajaxLoad(url)
    });

    function ajaxLoad(url) {
        query_params = {
            amount_show: $('#amount_show').val()
        };
        $('.data-table-pagination').html('<div class="loading">Loading...</div>')
        $.ajax({
            type: "GET",
            url: url,
            data: $.param(query_params),
            success: function(data) {
                $('.data-table-pagination').fadeOut('1000', function() { $(this).html(data) }).fadeIn('1000')
            }
        });
    }
});

How can I avoid this error when clicking on the pagination buttons:

<a class="page-link" data-target="index.php?page=2">2</a>

Error in image capture:

Before clicking on the page:

After clicking on the page:


Following the recommendations I have separated the code:

index.php

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
<div id="header">
    <div class="header">
        Hola
    </div>
</div>

<div id="wrapper">
    <div class="container">
        <div class="data-pagination">
            <div id="news-header" class="bootgrid-header container-fluid">
                <div class="row">
                    <div class="col-sm-12 actionBar">
                        <div class="search-bar">
                            <!--<input type="text" id="myInput" placeholder="What are you looking for?">-->
                            <input type="text" id="myInput" onkeyup="myFunction()" placeholder="What are you looking for?">
                        </div>
                        <div class="actions btn-group">
                            <select id="amount_show" name="amount_show">
                                <option value="10" <?php if ($records_by_page==10) echo "selected"; ?>>10</option>
                                <option value="25" <?php if ($records_by_page==25) echo "selected"; ?>>25</option>
                                <option value="50" <?php if ($records_by_page==50) echo "selected"; ?>>50</option>
                                <option value="100" <?php if ($records_by_page==100) echo "selected"; ?>>100</option>
                            </select>
                        </div>
                    </div>
                </div>
            </div>
            <div class="data-table-pagination">
                <?php echo $results_table; ?>
            </div>
        </div>
    </div>
</div>
<!-- THE AJAX CODE IS HERE -->
<script type="text/javascript" src="assets/js/pag.min.js"></script>

pagination.php

<?php
    $pagination_page = ''.$_SERVER['PHP_SELF'].'';
    $defaul_records = 10;

    if (isset($_GET['page'])) {
        $page = $_GET['page'] ?: '';
    }else{
        $page = 1;
    }

    if (isset($_GET['amount_show'])) {
        $records_by_page = $_GET['amount_show'];
    } else {
        $records_by_page = $defaul_records;
    }

    $localization_sql = ($page-1) * $records_by_page;

    $sql = "SELECT id_product,image,product,price_old,price
            FROM tbl_products
            WHERE active=1
            ORDER BY id_product ASC LIMIT $localization_sql, $records_by_page";
    $stmt = $con->prepare($sql);
    //$stmt->bind_param("i", $active);
    $stmt->execute();
    $stmt->store_result();

    if ($stmt->num_rows>0) :
        // http://php.net/manual/es/function.ob-start.php
        ob_start();
?>
    <table id="myTable employee_table" class="table table-condensed table-hover table-striped bootgrid-table">
        <thead>
            <tr>
                <th>ID</th>
                <th>IMAGEN</th>
                <th>PRODUCTO</th>
                <th>PRECIO</th>
                <th>ACCIÓN</th>
            </tr>
        </thead>
                <tbody>
        <?php
            $stmt->bind_result($id_product,$image,$product,$price_old,$price);
            while ($stmt->fetch()) {
                    echo '<tr>
                        <td>'.$id_product.'</td>
                        <td>';
                        echo'</td>
                        <td>'.$product.'</td>
                        <td>'.$price.'</td>
                        <td>
                            <span class="view_data" id="'.$id_product.'">Ver</span> |
                            <span class="edit_data" id="'.$id_product.'">Editar</span>
                        </td>
                    </tr>';
            }
            $stmt->close();
        ?>
        </tbody>
    </table>
    <div class="pagination">
        <ul class="pagination">
        <?php
            $sql = "SELECT * FROM tbl_products";
            $stmt = $con->prepare($sql);
            $stmt->execute();
            $stmt->store_result();

            $BD_records = $stmt->num_rows;
            $stmt->close();
            $con->close();

            $total_page = ceil($BD_records / $records_by_page);
            $prev = $page - 1;
            $next = $page + 1;

            if ($prev > 0) {
                echo "<li><a data-target='".$pagination_page."?page=1'><i class='icon-angle-double-arrow'></i></a></li>";
                echo "<li><a data-target='".$pagination_page."?page=$prev'><i class='icon-angle-left'></i></a></li>";
            }

            for ($i=1; $i<=$total_page; $i++) {
                if ($page==$i) {
                    echo "<li><a class='page-link active' >". $page . "</a></li>";
                } else {
                    echo "<li><a class='page-link' data-target='".$pagination_page."?page=$i'>$i</a></li>";
                }
            }

            if ($page < $total_page ) {
                echo "<li><a class='page-link' data-target='".$pagination_page."?page=$next'><i class='icon-angle-right'></i></a></li>";
                echo "<li><a class='page-link' data-target='".$pagination_page."?page=$total_page'><i class='icon-angle-double-right'></i></a></li>";
            }

            $results_table = ob_get_clean();

            else :
                $stmt->close();
            endif;

            if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
                echo $results_table;
                die;
            }
        ?>
        </ul>
    </div>

I have followed the recommendations, but here I have a new problem, I can't understand how to link the separate code now.

  • Can you add your html code also ? – Ajith Nov 24 '20 at 04:25
  • @Ajith It is the same code of this question friend https://stackoverflow.com/questions/52747673/how-to-display-the-page-with-ajax the only change I made is to change the name of the `.item` style to `.data-table-pagination` –  Nov 24 '20 at 04:28
  • Can you update the content inside after each paginate link click? I hope you get what i mean – Ajith Nov 24 '20 at 04:57
  • @Ajith if it is updated, the data is displayed without any problem, the only problem is that the headers and footer are inserted –  Nov 24 '20 at 05:07
  • @Ajith before click: https://i.imgur.com/DrfCfkI.png the error: https://i.imgur.com/56lMuv1.png –  Nov 24 '20 at 05:08
  • HI, did you tried separating whole php code in different page ? – Swati Jan 06 '21 at 14:55
  • @Swati Hi, Not because it makes me very confusing, the truth is that I like to have my code only `PHP` apart but in this case it is mixed between `HTML` and opening and closing keys `{}` with `tags / html code` : / –  Jan 06 '21 at 16:00
  • @Valentina you want first times it shows header & footer & after clicking on pagination links it does not shows header & footer ?? – KUMAR Jan 07 '21 at 23:45
  • @Valentina also tell me your header & footer part whichbyou want to hide?? – KUMAR Jan 08 '21 at 00:07
  • @KUMAR no friend, what I want is that the pagination works without those errors, I have been recommended to divide the code in a pagination.php –  Jan 08 '21 at 04:40
  • @KUMAR I tell him that these errors are not shown, since that content should not be loaded as seen in the images when passing to the next number of the pagination. –  Jan 08 '21 at 04:41
  • @Valentina so actually what you want shown in picture please?? – KUMAR Jan 08 '21 at 05:33
  • @KUMAR Hello friend, I want it to work normally like this: `https://i.imgur.com/DrfCfkI.png` and this does not happen: `https://i.imgur.com/56lMuv1.png` As you can see, the whole design of the header, footer or other content is inserted in the pager, well in conclusion, practically the entire page is inserted in the pagination result: `
    `
    –  Jan 08 '21 at 15:30
  • @Valentina when you marked green tick @swati answer then it means it solved your problem so why not `100 reputation bounty` is given to her? – KUMAR Jan 09 '21 at 08:17

1 Answers1

1

Your current page has htmls as well inside it so its bringing you html as well whenever you do ajax call so to avoid this one way would be making separate php-page .So, your current page will have php code as well that will execute on page load and one separate page that will get call whenever any a tag inside pagination is clicked .So, your current page will look like below :

<div id="header">
        <div class="header">
            Hello
        </div>
    </div>
    <div id="wrapper">
        <div class="container">
            <div class="data-pagination">
            <?php
                
                $pagination_page = 'pageurlwherephpcodeis';//only put here url of php page
                $defaul_records = 10;
                  //all same code of php which isthere
                ?>
               
            </div>
                   
        <!--put this div outside `data-pagination`..-->
         <div id="news-header" class="bootgrid-header container-fluid">
                <div class="row">
                    <!--same code-->
                </div>
            </div>
        </div>
       </div>
</div>

Now, ajax call should look like below :

function ajaxLoad(url) {
        query_params = {
            amount_show: $('#amount_show').val()
        };
       //change here selector
        $('.data-pagination').html('<div class="loading">Loading...</div>')
        $.ajax({
            type: "GET",
            url: url,
            data: $.param(query_params),
            success: function(data) {
              //change here selector
                $('.data-pagination').fadeOut('1000', function() { $(this).html(data) }).fadeIn('1000')
            }
        });
    }

Your php-page which will bring you output inside ajax call will somewhat look like below :

<?php
$strs = ''; //declre this
$pagination_page = 'pageurlwherephpcodeis'; //put here php page url
$defaul_records = 10;

if (isset($_GET['page']))
{
    $page = $_GET['page'] ? : '';
}
else
{
    $page = 1;
}

if (isset($_GET['amount_show']))
{
    $records_by_page = $_GET['amount_show'];
}
else
{
    $records_by_page = $defaul_records;
}

$localization_sql = ($page - 1) * $records_by_page;

$sql = "SELECT id_product,image,product,price_old,price
                            FROM tbl_products
                            WHERE active=1
                            ORDER BY id_product ASC LIMIT $localization_sql, $records_by_page";
$stmt = $con->prepare($sql);
$stmt->execute();
$stmt->store_result();

if ($stmt->num_rows > 0):

    ob_start();
    //append htmls to variables
    $strs .= '<table id="myTable employee_table" class="table table-condensed table-hover table-striped bootgrid-table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>IMAGEN</th>
                            <th>PRODUCTO</th>
                            <th>PRECIO</th>
                            <th>ACCIÓN</th>
                        </tr>
                    </thead>
                    <tbody>';

    $stmt->bind_result($id_product, $image, $product, $price_old, $price);
    while ($stmt->fetch())
    {
        $strs .= '<tr>
                                    <td>' . $id_product . '</td>
                                    <td></td>
                                    <td>' . $product . '</td>
                                    <td>' . $price . '</td>
                                    <td><span class="view_data" id="' . $id_product . '">Ver</span> |
                                        <span class="edit_data" id="' . $id_product . '">Editar</span>
                                    </td>
                                </tr>';
    }
    $stmt->close();

    $strs .= '</tbody></table><div class="pagination"><ul class="pagination">';

    $sql = "SELECT * FROM tbl_products";
    $stmt = $con->prepare($sql);
    $stmt->execute();
    $stmt->store_result();

    $BD_records = $stmt->num_rows;
    $stmt->close();
    $con->close();

    $total_page = ceil($BD_records / $records_by_page);
    $prev = $page - 1;
    $next = $page + 1;

    if ($prev > 0)
    {
        $strs .= "<li><a data-target='" . $pagination_page . "?page=1'><i class='icon-angle-double-arrow'></i></a></li>";
        $strs .= "<li><a data-target='" . $pagination_page . "?page=$prev'><i class='icon-angle-left'></i></a></li>";
    }

    for ($i = 1;$i <= $total_page;$i++)
    {
        if ($page == $i)
        {
            $strs .= "<li><a class='page-link active' >" . $page . "</a></li>";
        }
        else
        {
            $strs .= "<li><a class='page-link' data-target='" . $pagination_page . "?page=$i'>$i</a></li>";
        }
    }

    if ($page < $total_page)
    {
        $strs .= "<li><a class='page-link' data-target='" . $pagination_page . "?page=$next'><i class='icon-angle-right'></i></a></li>";
        $strs .= "<li><a class='page-link' data-target='" . $pagination_page . "?page=$total_page'><i class='icon-angle-double-right'></i></a></li>";
    }
    $str .= '</ul></div>';
    echo $strs; //echo will send back to ajax..
    else:
        $stmt->close();
        echo "no records..";
    endif;

?>
Swati
  • 28,069
  • 4
  • 21
  • 41
  • Hi, But where is this part of the code: ` –  Jan 08 '21 at 15:55
  • Its there see `
    – Swati Jan 08 '21 at 16:00
  • It does not show me anything friend, or error, or any data: / –  Jan 08 '21 at 16:05
  • not even your current page show any table or ul ? Your current page will be as it is only you need to make minor changes .. also don't forget to change `'pageurlwherephpcodeis'` here you need to put url of php page which is call by ajax . – Swati Jan 08 '21 at 16:09
  • On the page where there is only the php code, which I have called pagination.php if it shows data, but from the index.php it does not show me anything, it is not calling the friend data. –  Jan 08 '21 at 16:13
  • i see .. so inside `index.php` intial data are shown but when you click on `a` tag then nothing gets displayed ? If yes..first check if browser console has any error . – Swati Jan 08 '21 at 16:17
  • No friend in the index.php does not show any data, nothing is shown, only if I directly visit the pagination.php file only in that file it shows data ... And, in console it does not show me anything friend. –  Jan 08 '21 at 16:20
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/227047/discussion-between-swati-and-valentina). – Swati Jan 08 '21 at 16:21