I'm working with Laravel 5.8 and I am trying to set up pagination with live search via AJAX. I have configured it so that the pagination updates when the data is sent via a GET request due to the AJAX search. The only thing that isn't working is the link when I click to proceed to the next page.
When I click on a pagination link when the page is first loaded, the url looks like this http://localhost:8000/pagination?page=2
and it displays that page appropriately.
If I use my live search and click on a pagination link, the url looks like this http://localhost:8000/search?page=2
and doesn't display anything.
This is the AJAX in my pagination.blade.php
file:
$(function getResults(url) {
$('#search').on('keyup',function(){
$value=$(this).val();
$.ajax({
type: 'GET',
url: '{{URL::to('search')}}',
data:{ 'search':$value },
success:function(data){
console.log(data);
$('tbody').empty();
$('tbody').html(data);
},
error: function(err) {
console.log(err);
}
});
});
$(function() {
$('body').on('click', '.pagination a', function(e) {
e.preventDefault();
var url = $(this).attr('href');
getResults(url);
window.history.pushState("", "", url);
console.log(url);
});
});
This is my web.php
file:
Route::get('/search', 'SearchController@search');
Route::resource('/pagination', 'SearchController');
My pagination is rendered in my SearchController.php
file via $projects->render();
Let me know if you want me to include more code. I truly appreciate any help you can provide!
EDIT: Adding the SearchController.php
code:
public function index(Request $request)
{
$projects = Project::orderBy('name', 'asc')->paginate(5);
if ($request->ajax()){
return view('pagination_data', ['projects' => $projects])->render();
}
return view('pagination', compact('projects'));
}
public function search(Request $request)
{
if($request->ajax())
{
$projects=DB::table('projects')->where('name', 'LIKE', '%'.$request->search."%")->orwhere('description', 'LIKE', '%'.$request->search."%")->orderBy('name', 'asc')->paginate(5);
$resultCount = DB::table('projects')->count();
if($projects)
{
$output=$projects->render();
foreach ($projects as $project) {
$output.='<tr>'.
'<td>'.
'<a href="'. $project->link .'" target="_blank">'.
$project->name.
'</a>'.
'</td>'.
'<td>'.
$project->description.
'</td>'.
'<td>'.
$project->creator.
'</td>'.
'</tr>';
}
return Response($output);
}
else {
$output='<tr class="alert alert-danger" role="alert">No projects found :(</tr>';
return Response($output);
}
}
}
}
EDIT: I fixed the http://localhost:8000/%7B%7B$project-%3Elink%7D%7D
issue and I updated the code above.
EDIT, 6/1: I've narrowed down the issue further-- it seems like the pagination links are not updating after a live AJAX search is performed. http://localhost:8000/pagination?page=2
always refers to the original rows (before a search). I think the key to resolving this will be updating that initial link from the SearchController
file. Each time a live search is performed, the SearchController
code is pulled.