I am attempting to create ajax pagination using a "load more" button instead of Laravel's default pagination. Now, I've spent the past couple of days searching online for a solution, but everything is jquery and I am relatively new to javascript and Laravel. I'd prefer to avoid jquery, since I am trying to get better at working with vanilla javascript.
The index view paginates 4 items (for testing purposes at this point) and on each ajax request, I would like to render the next 4 rows.
My problem is, the ajax request renders the entire page instead of just the data from the database. What am I doing wrong in my code?
Controller:
public function ajax()
{
$products = Product::orderBy('title', 'asc')->paginate(4);
return $products;
}
Javascript:
const container = document.querySelector('#sandbox-container');
const button = document.getElementById('load-stuff');
let url = button.getAttribute('href'); // http://127.0.0.1:8000/sandbox?page=2
button.addEventListener('click', (event) => {
event.preventDefault();
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onload = function() {
if (xhr.status === 200) {
container.insertAdjacentHTML('beforeend', xhr.responseText); // ouputs html of entire view
console.log(`This is the response: ${xhr.responseText}`);
}
else {
console.log(`Request failed, this is the response: ${xhr.responseText}`);
}
};
xhr.send();
})
View: sandbox.blade.php
<div class="product-thumb-test-wrapper" id="sandbox-container">
@foreach ($products as $product)
<div>
<p >{{ $product->title }}</p>
<img src="/images/product/{{ $product->img }}" alt="{{ $product->title }}">
</div>
@endforeach
</div>
<div class="grid row" id="loaded-more">
</div>
<div class="grid">
{{ $products->links('vendor.pagination.default') }}
</div>
I am not sure what I need to do in order to render the xhr.responseText as only the $products data? I've tried sending it as json data, but that returns null each time. I hope someone can help a noob out here, thanks in advance!