To deal with AJAX search in Laravel, you can use the following steps:
-
Create a search form in your view file with an input field and a search button.
-
Create a route in your web.php file that will handle the AJAX request.
-
In your controller, create a function that will handle the AJAX request and return the search results.
-
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:
- 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>
- Create a route in your web.php file:
Route::get('/search', 'SearchController@search')->name('search');
- 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,
]);
}
- 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.