Maintaining search and sort state across paginated results in web application

49 Views Asked by At

I'm working on a web application where users can search for data and paginate through the results. I've implemented search functionality, allowing users to search for specific data and sorting functionality to sort the results based on certain criteria.

However, I'm facing two main issues:

Search State Persistence: When users navigate to the next page of results, the search query gets reset, and they lose the search context. How can I ensure that the search query persists across pagination so that users can continue browsing results based on their original search?

Sorting State Issue: Additionally, although sorting works fine on the first page of results, when users navigate to subsequent pages, the sorting seems to reset, and the results are not consistently sorted as expected. How can I maintain the sorting state across all pages of results?

I've checked my code thoroughly, but I'm unable to identify the exact issue causing these problems. Could someone please provide insights or suggestions on how to address these issues and ensure a seamless user experience with search and sorting functionality across paginated results?

adminUserList.php

session_start();
if (!isset($_SESSION['sort_order'])) {
    $_SESSION['sort_order'] = ''; // Set default sort order if not set
}

// Store sorting order in session
if (isset($_POST['sort_order'])) {
    $_SESSION['sort_order'] = $_POST['sort_order'];
var_dump($_SESSION);
}

$limit = 5;
$searchValue = isset($_POST['search']) ? $_POST['search'] : '';
$sortOrder = isset($_POST['sort_order']) ? $_POST['sort_order'] : '';

$page = isset($_POST["page_no"]) ? $_POST["page_no"] : 1;
$sno = ($page - 1) * $limit + 1;

if ($searchValue !== "") {
    $result = $database->searchUser($searchValue, (int)$limit);
    $total_record = $database->getTotalRecords(['f_name'], $searchValue);
    $total_page = ceil($total_record / $limit);
    echo $twig->render('adminUserList.twig', ['result' => $result, 'total_page' => $total_page, 'current_page' => $page, 'sno' => $sno, 'searchValue' => $searchValue, 'email' => $email, 'sortOrder' => $_SESSION['sort_order']]);
} elseif ($_SESSION['sort_order']) {
    $result = $database->getUsersSorted($_SESSION['sort_order'], $limit); // Corrected 
    $total_record = $database->getTotalRecords();
    $total_page = ceil($total_record / $limit);
    echo $twig->render('adminUserList.twig', ['result' => $result, 'total_page' => $total_page, 'current_page' => $page, 'sno' => $sno, 'email' => $email, 'sortOrder' => $_SESSION['sort_order']]);
} else {
    // Handle case when neither search nor sorting is applied
    $result = $database->selectAllUser($limit, $page);
    $total_record = $database->getTotalRecords();
    $total_page = ceil($total_record / $limit);

admin.js file for handel ajax

    // Function to load table data
    function loadTable(page = 1, fn) {
        $.ajax({
            url: "adminUserList.php",
            type: "POST",
            data: {
                page_no: page,
            },
            success: function (data) {
                $("#table-data").html(data);
                fn?.();
            }
        });
    }
   
    // Search code
    function loadSearch(page = 1,oder) {
        var search_term = $("#searchInput").val();
        $.ajax({
            url: "adminUserList.php",
            type: "POST",
            data: {
                search: search_term,
                page_no: page,
                sortOrder:oder,

            },
            success: function (data) {
                $("#table-data").html(data);
            }
        });
    }

    // Trigger search on keyup
    $(document).on("keyup", "#searchInput", function () {
        loadSearch();
    });

    // Code for pagination search
    $(document).on("click", ".page-item a", function (e) {
        e.preventDefault();
        var page_id = $(this).attr("id");
        console.log(page_id)
        loadSearch(page_id);
    });

    // Sorting code
    $(document).on("change", "#sort-order", function () {
        var sortOrder = $(this).val();
        sortTable(sortOrder);
    });

    // Function to sort table
    function sortTable(order) {
        console.log(order);
        var page_id = $(".pagination .active").find("a").attr("id");
        console.log(page_id);
        $.ajax({
            url: "adminUserList.php",
            type: "POST",
            data: {
                page_no: page_id,
                sort_order: order
            },
            success: function (data) {
                $("#table-data").html(data);
            }
        });
    }

twig file

                  <select id="sort-order" class="btn btn-secondary">
                <option value="ASC">Ascending</option>
                        <option value="DESC">Descending</option>
                    </select>
                </th>
                <th scope='col'>Email-Id</th>
                <th scope='col'>Phone-No</th>
                {% if result is not empty %}
                    {% for row in result %}
                        <tr>
                            <td>{{ sno }}</td>
                            <td>{{ row['f_name'] }} {{ row['l_name'] }}</td>
                            <td>{{ row['email'] }}</td>
                            <
                                <button type='button' class='btn btn-info' data-eid='{{ row['uid'] }}'>view</button>
                                <button type='button' class='btn btn-danger' data-id='{{ row['uid'] }}'>Delete</button>
                            </td>
                        </tr>
                        {% set sno = sno + 1 %}
                    {% endfor %}
                {% else %}
                    <tr>
                        <td colspan="8">
                            <h2>No Records Found</h2>
                        </td>
                    </tr>
                {% endif %}
            </tr>
        </table>
        <!-- Pagination controls -->
<nav aria-label="Page navigation">
    <ul class="pagination">
        {% if total_page > 0 %}
            {% for page_num in 1..total_page %}
                {% if searchValue != "" %}
                    <li class='Search-item {% if page_num == current_page %}active{% endif %}'>
                        <a class="page-link" href="?page={{ page_num }}&search={{ searchValue }}" id="{{ page_num }}">
                            {{ page_num }}
                        </a>
                    </li>
                {% else %}
                    <li class='page-item {% if page_num == current_page %}active{% endif %}'>
                        <a class="page-link" href="?page={{ page_num }}" id="{{ page_num }}">
                            {{ page_num }}
                        </a>
                    </li>
                {% endif %}
            {% endfor %}
        {% else %}
            <li class="page-item disabled">
                <span class="page-link">
                    No Records Found
                </span>
            </li>
        {% endif %}
    </ul>
</nav>

1

There are 1 best solutions below

0
GetSet On

The problem of not having "Search State Persistence" arises because adminUserList.php is apparently initially posted to thus you use $_POST to get the params, but then your generated pagination are just anchor tags, where you'd need to use $_GET to get at the params, which you dont have.

There are at least two ways to correct the issue:

(1) Modify your page that initially posts to adminUserList and make it pass the params on the url itself. Then in adminUserList.php change each $_POST to $_GET.

(2) The 2nd way is to modify adminUserList.php so that it can handle both post and get type params.