chilldsgn
chilldsgn

Reputation: 47

Laravel ajax pagination loads entire page

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.

I have tried all the suggestions on this site that I could find, none works for me.

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 sandbox(Request $request)
    {

        $response = array(
            'status' => 'success',
            'msg' => $request->message,
        );

        $products = Product::orderBy('title', 'asc')->paginate(4);

        if ($request->ajax()) {
            return view('sandbox-more', compact('products'))->render();
        }
        else {
            return view('sandbox', compact('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 entire view instead of the partial
            console.log(xhr.responseText);
        }
        else {
            console.log(`Request failed, this is the response: ${xhr.responseText}`);
        }
    };

    xhr.send();     
})

My partial view to be loaded on ajax request

@foreach ($products as $product)
    <div style="background-color:pink; width: 200px;">
        <p>{{ $product->title }}</p>
        <img src="/images/product/{{ $product->img }}" alt="{{ $product->title }}" style="width: 50px;">
    </div>
@endforeach

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!

Upvotes: 1

Views: 638

Answers (1)

chilldsgn
chilldsgn

Reputation: 47

I managed to fix it using xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');

Upvotes: 1

Related Questions