Reputation: 629
I'm using laravel to fetch huge amount of data from database (100mil++ data), but it was giving me error which is timeout because loading the data is too long, and i want to use AJAX to append the data in Laravel view gradually by calling the controller, and then the controller fetch the data using query with LIMIT, so the view will gradually displaying data in accordance with the limited data, so it wont be timeout
controller :
public function index(){
return view('users.index',compact('users'));
}
public function loadAjax(){
// print_r('expression');
$counter = Input::get('counter');
$users = User::take(1)->skip($counter)->get();
return json_encode($users);
}
jquery and AJAX:
<script>
var ctr = 0;
window.onload = function () {
getData();
};
window.setInterval(function () {
ctr++; //increase the data offset
getData();
}, 1000);
function getData() {
jQuery(document).ready(function() {
jQuery.ajax({
url: "users/ajax",
type: 'GET',
data: {counter : ctr},
dataType: "json",
success: function(data) {
console.log(data.users);
for(var i =0; i < data.users.length; i++) {
var htm = '';
htm += '<tr id="inside">'
htm += '<td>'+data.users[i].id+'</td>';
htm += '<td>'+data.users[i].name+'</td>';
htm += '<td>'+data.users[i].email+'</td>';
htm += '</tr>'
$("#inside").append(htm);
}
},
error: function(data) {
}
});
});
}
</script>
routes :
Route::get('users/ajax','UserController@loadAjax');
the problem is i'm new with ajax and idk if my method is the right way
Upvotes: 0
Views: 1824
Reputation: 151
The pagination pattern you're describing is called Infinite Scroll. The first x records would load on the page, and subsequent AJAX calls request more data and add it to the list in the view. Here is a Laracast with more info on implementing Infinite Scroll. Infinite scroll requests are triggered from onScroll events when the scroll has reached a bottom. Alternatively, a button can be used to trigger the next request.
Keep in mind that you will not be able to display all the records ever in the browser because of client memory limitations. Generally millions of objects do not work great in the DOM. Consequently large data sets do not lend themselves well to Infinite Scroll. I'd strongly recommend plain old pagination.
An out of the box pagination toolkit with AJAX that works well with large data sets is jQuery Datatables. Good luck.
Upvotes: 1