Implementing Laravel pagination to retrieve data through ajax calls

I am currently working on setting up a pagination feature using Laravel. When it comes to the backend, I have set up my JSON response in the following way:

        if(isset($request->myDate)) {

            $request->validate([
                'myDate'  => 'required|date',
            ]);

            $start_date = $request->get('myDate');
            $end_date = Carbon::now();

            $my_tickets = Ticket::where('admin_id', Auth::user()->id)->whereBetween('updated_at', [$start_date, $end_date])->with(['getAdmin'])->paginate(10);

    }   

    return json_encode($my_tickets);

As for the frontend part, I'm utilizing AJAX requests to show the rows. My main query now is how do I integrate the pagination system? Are there any built-in features in Laravel or external components that can simplify this task? Do I need to develop the front end myself since I cannot utilize the $var->links() function as when returning a view?

Warm Regards

Answer №1

When working with the frontend Response, you have access to valuable information such as the page number, total count, and items per page. If you are looking to implement custom ajax pagination, consider using the code snippet below in your ajax calls.

  var page = ''
                    var count = 0;
                    if (response.total > response.perPage) {
                        if (response.page != 1) {
                            page += '<li class="page-item"><a class="page-link" data-page="' + (response.page - 1) + '" href="#">' + 'Previous' + '</a></li>'
                        }
                        for (i = response.page; i <= response.totalPage; i++) {
                            count++;

                            if (response.page == i) {
                                page += '<li class="page-item active"><a class="page-link" data-page="' + i + '" href="#">' + i + '</a></li>'
                            } else {
                                page += '<li class="page-item"><a class="page-link" data-page="' + i + '" href="#">' + i + '</a></li>'
                            }

                            if (count == 10) break;
                        }
                        $('.number-of-show').append(' Showing ' + ((response.perPage * (response.page - 1)) + 1) + ' to ' + response.perPage * response.page + ' of ' + response.total);
                        $('.pagination').append(page);
                    }

Within the controller:

   $page = '';
        if (!empty($data['page'])) {
            $page = $data['page'];
        }
        $params['totalPages'] = ceil($paramsData['total'] / $params['perPage']);
        $params['offset'] = ($page - 1) * $params['perPage'];

        $withdrawRequestLists = $paramsData['data'];
        $total = $paramsData['total'];
        $totalPage = ceil($total / $params['perPage']);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The message sent from the server via SocketIO seems to be malfunctioning

Currently, I am in the process of developing an application that utilizes websockets for facilitating server-client communication. The main idea behind this concept is to enable the client to request messages from the server, while also allowing the server ...

Can passing parameters between nested map functions cause any issues?

While attempting to navigate to a page in reactjs and pass parameters using the useNavigate hook, I encounter an unexpected token error as soon as I include the navigation within the anchor tag. <a onClick={() ={ ...

Introducing Block Insert feature in React Draft-js - a powerful

How the Process Works: Upon hitting the spacebar, the Draft-JS editor queries the text content for a specific word. Subsequently, all instances of that word are enveloped in tags. The HTML is then converted back and the state of the Draft-JS editor is upd ...

Avoid making an Ajax request in CodeIgniter if there is no active session or if the network is disconnected

I am currently facing two challenges in my project. I would greatly appreciate it if someone could assist me with resolving them. One issue I am encountering is with the use of the .load() function in JavaScript to load another page using Ajax. While i ...

Please display the Bootstrap Modal first before continuing

Currently, I'm facing a challenge with my JS code as it seems to continue running before displaying my Bootstrap Modal. On this website, users are required to input information and upon pressing the Save button, a function called "passTimeToSpring()" ...

Switch up the Javascript popup code without any specific pattern

I am looking to add variety to my pop up ads on my website by randomly changing the Javascript code for each ad every time a page is loaded. How can I achieve this? Script 1 <script type="text/javascript"> var uid = '12946'; var w ...

What is the best way to incorporate parallax scrolling in the center of a webpage?

I am trying to implement a parallax scrolling effect in the middle of my page, but it seems to be causing issues once I reach that section while scrolling. I attempted to use intersection observer, but unfortunately, it did not resolve the problem. const ...

Setting a false condition on jQuery's .on('canplaythrough') event

Struggling to implement a custom audio control with jQuery, but encountering some issues. I'm in the process of converting native JavaScript to jQuery for consistency in my code, however, I can't seem to get it working. The original code that is ...

When trying to access the "form" property of a form ElementRef, TypeScript throws an error

I've encountered an issue with accessing the validity of a form in my template: <form #heroForm="ngForm" (ngSubmit)="onSubmit()"> After adding it as a ViewChild in the controller: @ViewChild('heroForm') heroForm: ElementRef; Trying ...

"Error 404: The file you are looking for cannot be found on [custom company domain]. Please check

My attempts to retrieve a Google Drive file using its file ID with a service account in NodeJS have been unsuccessful. The requests are failing with an error indicating a lack of access: code: 404, errors: [ { message: 'File not found: X ...

The chosen option in the q-select is extending beyond the boundaries of the input field

Here's the code snippet I used for the q-select element: <q-select square outlined fill-input standout="bg-grey-3 text-white" v-model="unit_selection" :options="units&qu ...

How can I convert JSON data from an array to an array of objects using JavaScript?

My goal is to load data into an ag-grid. I have obtained the json data in the following format: {"my_data":{"labels":[1,2,3,...], "idx":["idx1", "idx2", ...]}} In order to pass it to the grid, I need to transform it to this format: {"my_data":[{"labels" ...

The current date is cycling back to the month before

There is a datetime received from my api as 2018-09-01T00:00:00.000Z, referred to as frame.scandate. Another date is generated within the program as 2018-09, simply known as scandate. These examples can represent any year/month combination. In my code: ...

Is it possible to organize words with HTML elements utilizing JavaScript?

Code is not properly sorting the elements var element='<p><strike>Mango</strike></p>/n<p><em>Orange</em></p>/n<h1>Apple</h1>/n<p><strong>banana</strong></p>/n<p& ...

Error message: The name of the variable is not defined - Attempting to transfer an array from a Ruby file to

We utilize a Mysql database and haml files for our project. Currently, we are facing an issue when dynamically generating a table with data from the mysql database. It triggers this error: NameError - undefined local variable or method `allsites' fo ...

What is the best way to combine the existing array data with the previous array data in JavaScript?

I am implementing server-side pagination in my MERN project. Let's say I retrieve 100 products from the database and want to display only 30 products, with 10 products per page. When a user navigates to the 4th page, I need to make another API call to ...

Receiving a 500 status code upon converting a SqlDataReader into Json format

Getting a status 500 error and not sure where I am going wrong. When I click on the 'Getcustomers' button, the 'GetCustomers' method is called which returns JSON. Script: <script> var MyApp = angular.module("MyApp", []); ...

Expanding Java Classes and Replacing Methods with Multiple Parameters in ES4X/Graal

I am currently facing a challenge in my JavaScript project using ES4X/Graal, where I need to extend a Java class. This Java class has methods with overloaded parameters that I must override. While I understand how to call a specific Java method by specifyi ...

Ways to extract specific HTML from a jQuery element

When fetching html from a website, how can I extract specific html content instead of getting all of it? I have attempted the following method: Before appending data to the target below container.html(data); I would like to perform something like data.f ...

The componentDidMount function is not initializing the state

I am trying to access the references from the render function and then set them to the state. Below is my code snippet: class App extends Component { constructor(props) { super(); this.arr = this.generateTimelineArray(); ...