Refreshing and paginating data tables

I'm currently working on a basic CRUD data table and I have added a refresh function using AJAX to dynamically append HTML without reloading the page. Everything was working fine until I introduced pagination from Laravel. The issue now is that only the first 5 data entries are displayed on each subsequent page.

$(document).ready(function() {
  // Function to refresh table data
  function refreshTable(page) {
      $.ajax({
          url: '/get-latest-projects?page=' + page, // URL to fetch updated data
          method: 'GET',
          success: function(response) {
              // Update table with new data
              $('#dataTable tbody').html(' '); // Assuming data is in HTML format for the table body only

              $.each(response.data, function(index, item) {
                var row = '<tr class="tr">';
                row += '<td>' + item.input_date + '</td>';
                row += '<td>' + item.nama_project + '</td>';
                row += '<td class="desc">' + item.requestor + '</td>';
                row += '<td>' + item.category_project + '</td>';
                row += '<td><span>' + item.description_project + '</span></td>';
                row += '<td>' + item.status + '</td>';
                row += '<td><span class="status--process">' + item.pic_project + '</span></td>';
                row += '<td>' + item.eta_project + '</td>';
                row += '<td><div class="table-data-feature" id="editContainer">';
                row += '<button type="button" class="item" data-toggle="modal" data-target="#editModal' + item.id + '" data-placement="top" title="Edit"><i class="zmdi zmdi-edit"></i></button>';
                row += '<button class="item" data-toggle="tooltip" data-placement="top" title="Delete"><i class="zmdi zmdi-delete"></i></button>';
                row += '</div></td></tr>';
                $('#dataTable tbody').append(row);
            });
          },
          error: function(xhr, status, error) {
              console.error('Error refreshing table:', error);
          }
      });
  }

  refreshTable(1);

  // Reload table when the button is clicked
  $('#reloadButton').click(function() {
      refreshTable(1);
  });
});

The table briefly displays the next page's data before being overwritten by newly fetched data from the appended HTML content.

    public function index()
    {
        $projects = Project::orderBy('id', 'desc')->paginate(5);
        return view('table', compact('projects'));

    }


    
    public function getLatestProjects()
    {
        $projects = Project::orderBy('id', 'desc')->latest()->paginate(5); // Adjust as needed
        return response()->json($projects);
    }

This attempt aims to address the issue of an undefined object experienced previously.

Answer №1

It seems that the issue you are facing is related to how the pagination of your table data is being handled along with the use of AJAX to refresh the table content. The problem arises when refreshing the table with new data, as Laravel's pagination system may conflict with the manual update process.

To resolve this issue, it is important to adjust your approach in handling pagination properly within your AJAX requests. Here are some steps you can take:

Make changes to your JavaScript code to ensure the page number is included in the AJAX request:

$(document).ready(function() {
  // Function for refreshing table data
  function refreshTable(page) {
      $.ajax({
          url: '/get-latest-projects?page=' + page, // Make sure to include the page number in the URL
          method: 'GET',
          success: function(response) {
              // Update the table with new data
              $('#dataTable tbody').html(' '); // Assuming data is in HTML format for the table body

              $.each(response.data, function(index, item) {
                  // Add new rows to the table
              });

              // Update pagination links if necessary
              $('#pagination').html(response.links); // Update pagination links
          },
          error: function(xhr, status, error) {
              console.error('Error while refreshing the table:', error);
          }
      });
  }

  refreshTable(1);

  // Reload the table when the button is clicked
  $('#reloadButton').click(function() {
      refreshTable(1);
  });

  // Handle pagination clicks
  $(document).on('click', '.pagination a', function(event) {
      event.preventDefault();
      var page = $(this).attr('href').split('page=')[1]; // Extract page number from the URL
      refreshTable(page);
  });
});

Furthermore, in your Laravel controller, ensure that both the data and pagination links are returned in the JSON response:

public function getLatestProjects()
{
    $projects = Project::orderBy('id', 'desc')->latest()->paginate(5); // Adjust as required
    return response()->json([
        'data' => $projects->items(), // Retrieve the data items
        'links' => $projects->links()->toHtml(), // Obtain pagination links in HTML format
    ]);
}

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

Trouble fetching data for my controller in AngularJS using UI Router resolve

My attempts to inject a resolve object containing loaded data into my controller are resulting in an Unknown Provider error : Error message: Unknown provider: configServiceProvider <- configService Below is the code I am working with: StateProvider ...

The 'admin' attribute is not found in the 'Object' data type

I have been facing this issue for quite some time now. The backend API response is indicating that a certain property does not exist, even though it clearly does. My Angular application suddenly started showing 18 errors today, and I am at a loss on how ...

Eliminate the hover effect from every element

Is there a method in CSS or Javascript that allows me to eliminate the hover effect on all elements? I am specifically looking for a solution that will disable the hover effect on mobile devices while keeping it intact on desktop. I attempted using pointer ...

What is preventing PHP from accessing the $_SESSION[] array?

I have a PHP code that processes a large amount of data, sometimes interactively. In my initial PHP page, I ensure to call the function session_start() before sending any other information to the browser. I then store some data in the $_SESSION[] array usi ...

What is the method for exporting data directly from an EC2 instance to a file, such as a .txt or .json file?

I tried exporting the security group rules from EC2 into a file, like .txt or .json, using javascript/node.js. However, my attempts were unsuccessful. I wrote a code to retrieve information about security groups (rules, ingress, egress, etc.) and save it ...

Is there a way to extract the properties of a CSS class from a stylesheet and convert them into a hash using JavaScript or jQuery?

I am exploring a way to extract key value pairs from a CSS stylesheet related to a specific class or id into a JavaScript object for data accessibility. It is important to mention that I do not intend to apply this class directly to any DOM elements. In ...

How can I prevent users from inputting negative numbers in a cellEditable material-table?

In my project, I am utilizing a material table with editable cells. I need to implement a restriction that prevents users from entering negative numbers in the field and displays an error validation message. How can I achieve this functionality? Check out ...

The importance of manually loading extensions and utilizing Ajax effectively for renderPartial

Within my yii application, I have implemented Tabs and am loading content via ajax using renderPartial(). To prevent redundant script loading, I have set processOutput to false. As a result, I aim to manually load all necessary scripts once on the index pa ...

How can I link the function name stored in JSON data to the (click) event of a button in an Angular project?

Seeking assistance with assigning method names dynamically and utilizing them in my code. Here is what I have attempted so far: <div class="dashboard row"> <div class="card col-lg-3" *ngFor="let card of cards"> <h5 class="card-title"> ...

I am experiencing difficulty in successfully transmitting a variable from my jQuery code to my PHP code

I've been attempting to pass a variable from my jQuery code to my HTML/PHP code using AJAX and POST. However, I'm encountering an error message stating "Notice: Undefined index: testData in C:\xampp\htdocs\teszt\test1.php on l ...

What is the most effective approach for managing nested callbacks in Node.js/Expressjs?

My server side coding is done using Node.js and Expressjs, with MongoDB as the backend. Although I am new to these technologies, I need to perform a list of actions based on requests. For example, in user management: Check if the user is already registe ...

Unique: "Best Practices for Setting Angular.js Controller Data Directly in the Code"

In this scenario, I need to initialize the data from an inline script, even though I know how to achieve this using a promise on an http request. Currently, the controller is already defined in the header js: var testModule = angular.module('myTestM ...

Using AJAX to send an array as a response from Laravel

After implementing Laravel to handle an AJAX post request, I encountered an issue with displaying the route data. public function infoRoute(Request $request) { // Extracting required information $ship_id = $request->ship_id; ...

"Transforming the Website Background with a Splash of Color

I am trying to figure out how to change the color scheme of my website with a button click. Currently, when I select a different color, only the background of the webpage I'm on changes, not the entire website. I have applied CSS but it's not ref ...

Dealing with the challenge of managing multiple instances in a setup involving Ajax long polling (comet) and PHP on Lighttpd v1

I am a newcomer to this platform, so I hope to provide all the necessary details about my question. I have been attempting to set up a mechanism for "new message arrived notification" using long polling. Currently, I am triggering the polling request thro ...

Include a header in the API HTTP call for Angular 2 and Ionic 2

Working on my Ionic 2 app, I am using Angular 2 Http to retrieve JSON from an API. However, I am struggling to send the app-id, app-key, and Accept as headers in the main code snippet below: import {Component} from '@angular/core'; import {NavC ...

Tips for concealing JavaScript files from the Chrome Developer Tools while using Next.js

Currently working on a project using Next.js. I've noticed that the utils/components are quite visible through the Chrome Developer Tools, as shown in this image: https://i.sstatic.net/jaLmg.png Is there a way to hide them from being easily accessib ...

What is the best way to create an optional object parameter in Typescript?

I'm working on a function that looks like this: const func = (arg1: string, { objArg = true }:{ objArg: string }) => { // some code } Is it possible to make the second parameter (an object) optional? ...

Failure of Ajax to populate dropdowns in Internet Explorer

I've been grappling with some code for the past couple of days and I'm stuck. I really need some help. Here's what I'm trying to achieve: Manually fill the first dropdown menu Retrieve the selected value from the first dropdown, use i ...

What is the best way to combine several plugins in tinymce?

I experimented with a basic code snippet to test tinyMCE, and everything is functioning properly. However, I encountered an issue when attempting to add multiple plugins simultaneously. In this instance, I utilized the tinymce CDN for reference. Below is ...