ShamiCanCode's avatar

how to deal with ajax search in laravel

like users table now i want to do ajax search but the problem is pagination

if i send pagination like

   return response()->json([
            "result" => view(
                'dashboard.withdraw-history.search-results',
                compact('withdrawHistories')
            )->render(),
            "pagination" => $withdrawHistories->links("pagination.custom")->render(),
        ]);

but the problem is when I click on pagination laravel sends me a response in JSON

0 likes
3 replies
LaryAI's avatar
Level 58

To deal with AJAX search in Laravel, you can use the following steps:

  1. Create a search form in your view file with an input field and a search button.

  2. Create a route in your web.php file that will handle the AJAX request.

  3. In your controller, create a function that will handle the AJAX request and return the search results.

  4. In your view file, add a JavaScript function that will handle the AJAX request and update the search results on the page.

Here's an example of how you can implement this:

  1. Create a search form in your view file:
<form id="search-form">
    <input type="text" name="search" placeholder="Search...">
    <button type="submit">Search</button>
</form>

<div id="search-results"></div>
<div id="pagination-links"></div>
  1. Create a route in your web.php file:
Route::get('/search', 'SearchController@search')->name('search');
  1. In your controller, create a function that will handle the AJAX request and return the search results:
public function search(Request $request)
{
    $search = $request->input('search');

    $withdrawHistories = WithdrawHistory::where('name', 'like', '%'.$search.'%')->paginate(10);

    $view = view('dashboard.withdraw-history.search-results', compact('withdrawHistories'))->render();
    $pagination = $withdrawHistories->links('pagination.custom')->render();

    return response()->json([
        'view' => $view,
        'pagination' => $pagination,
    ]);
}
  1. In your view file, add a JavaScript function that will handle the AJAX request and update the search results on the page:
<script>
    $(document).on('submit', '#search-form', function(e) {
        e.preventDefault();

        var search = $('input[name="search"]').val();

        $.ajax({
            url: '{{ route('search') }}',
            type: 'GET',
            data: {
                search: search
            },
            success: function(response) {
                $('#search-results').html(response.view);
                $('#pagination-links').html(response.pagination);
            }
        });
    });
</script>

This will allow you to perform an AJAX search and update the search results and pagination links on the page without refreshing the page.

jlrdw's avatar

@ShamiCanCode in Ajax I usually make a custom next and previous button or I use a server fetched partial.

Please or to participate in this conversation.