sanakran's avatar

Generate own link instead of pagination render default link - laravel 5.0

Developed one new laravel 5.0 app. There I have used ajax concept for every pages. Each and every request and response will travel through ajax.

Main Page:

   <onclick="view('bydproject')">View ByDProject Data <> (inside li tage)
    <  id='main'> (Inside div tag)

Ajax call :

function view(url)
{
    fullurl = "http://localhost:8000/" + url ;
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function(){
    if(xhttp.readyState == 4 && xhttp.status == 200)
    {
        document.getElementById("main").innerHTML = xhttp.responseText;
    }
    };
    xhttp.open("GET", fullurl, true);
    xhttp.send();
}

In one of the case, I have used pagination concept for some page.

Conctroller:

$employees = ByDEmployee::paginate(20);
return view('bydemployee.view_all_employees', compact('employees'));

view_all_employees.blade.php

@foreach($employees as $employee)
      {{ $employee->first_name }}
      //Display 
@endforeach
{{ $employees->render() }}

In this situation pagination render link generate that own link. instead of that link I have to generate my ajax call? whether it is possible ?

Ex: Instaed of this (Default url. copied from browser->view source page)

<li><a href="http://localhost:8000/bydemployee?page=2" rel="prev">«</a></li> 

Link looks like this

<li><a onclick=view('bydemployee?page=2') rel="prev">«</a></li> 
0 likes
6 replies
Snapey's avatar

You should probably pass the whole list to the browser and then implement pagination in ajax?

Alternatively pass the paginator object to your page in json and use it to inform your pagination buttons so that you can make the correct request.

pmall's avatar

instead of that link I have to generate my ajax call?

Add an event on click on the link. Then prevent defaults, grab the href and make your ajax call from the url. Learn about unobtrusive javascript.

sanakran's avatar

"Add an event on click on the link"

How does add event on click. It automatically generated by pagination render right. Where I have to change default link?

Snapey's avatar

Are you pulling in the content and then just inserting the full html into the current page?

I'm assuming you are not using a javascript framework?

jekinney's avatar

Depending on the data size/performance I set a data-attribute that has the Json object passed in through the controller as normal so the data is avalible when the page loads. Not load page the Ajax call. I then set up JavaScript to set up the pagination on the Json object. This also allows the benefit of sorting and searching with out hitting the database again along with pagination. JavaScript is so much faster (more so on the sort and search) then a bunch of Ajax calls.

Data tables does this process. Though the con is if you have a large amount of data it breaks down and smaller Ajax calls work better.

Please or to participate in this conversation.