Adding parameters to TR or TDs in DataTables 1.10.5 via Ajax: A step-by-step guide

My goal is to dynamically load datatable data using AJAX and customize the rows and cells by adding parameters such as classes or 'data' attributes. The challenge lies in utilizing a PHP helper that generates JavaScript code, as shown below:

$datatables = array(
            'type' => array(
                'bAutoWidth' => false,
                'ajax' => site_url('admin/parameters/area_add_type_table_data_ajax/' . $t_id),
                'paging' => false,
                'searching' => true,
                'columns' => array(
                    array('width' => '20%', 'class' => 'text-center')
                ),
                'info' => true,
                'scrollX' => true,
            ),
        );

This PHP array gets JSON-encoded to create the necessary JavaScript for rendering the table.

Additionally, the AJAX source provides a JSON-encoded array with data like this:

$data = array('data' => array(array('SOME TEXT HERE...'), array('SOME TEXT IN ANOTHER ROW...')); exit(json_encode($data);

An example row generated from this code is:

<tr role="row" class="odd"><td class="text-center">SOME TEXT HERE...</td></tr>

However, I also need to include some "parameters" in the final rows (tr) and certain cells (tds) indicated by attributes enclosed in double asterisks.

<tr role="row" class="odd" **data-id="##"**><td class="text-center" **data-content="unit_short" data-id="##"**>SOME TEXT HERE...</td></tr>

These IDs depend on the current data in the row, making them variable.

I'm open to any suggestions or solutions, whether it be modifying the existing PHP implementation or implementing a solution purely in JavaScript.

Answer №1

Understanding the functionality of your PHP helper may vary, however, utilizing the createdRow callback can help achieve this:

createdRow: function(tr, data, index) {
   $(tr).attr('data-id', '##');
   $('td', tr).eq(1)
              .attr('data-content', 'unit_short')
              .attr('data-id', '##')
}

The usage of ## in the context is not clearly specified, but taking this approach would be a step forward. In scenarios where there is no explicit ##, consider utilizing the index.

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

Transform data into JSON format using the stringify method

I am facing an issue with my TypeScript code where I need to retrieve specific information from a response. Specifically, I want to output the values of internalCompanyCode and timestamp. The Problem: An error is occurring due to an implicit 'any&apo ...

When I click on .toggle-menu, I want the data-target to have a toggled class and the other divs to expand

Looking to achieve a functionality where clicking on .toggle-menu will toggle a class on the specified data-target element and expand other divs accordingly. jQuery(document).ready(function() { var windowWidth = jQuery(window).width(); if (win ...

Need to convert an HTML table to JSON format? Visit convertjson.com/html-table-to-json.htm to easily convert your HTML table

Can anyone help me with converting HTML table data to JSON? I found a website that does something similar: I have tried some solutions but encountered issues at the end. I just need a JSON output to convert it into an array and continue with my project. ...

Implementing file uploads with Bootstrap, jQuery, and Laravel

Looking to incorporate the blueimp jquery file upload feature into my Laravel app. Check it out here: https://github.com/blueimp/jQuery-File-Upload The form is set up and working properly with the plugin, but facing issues with creating server-side script ...

How can I troubleshoot my inability to map JSON object data in Next.js?

I have been working on displaying JSON data retrieved from the backend. The process involves using a useEffect hook to fetch the data: const [backendData, setBackendData] = useState(null) useEffect(() => { const fetchUserData = async () => { ...

Storing information in a database without the need for a page refresh using ajax in laravel

My form allows users to input multiple fields and save them to a database using AJAX. Below is the HTML for my form: <form id="paramsForms" method="POST"> {{csrf_field()}} {{ method_field('POST') }} <div class="modal-body" ...

Expanding the List View with JSON data

Is there a way to implement an ExpandableListView that retrieves data from a server response in JSON array format for both its groups and children? I have used SimpleCursorTreeAdapter before, but it only works with cursors. I'm looking for an equiva ...

Tips for combining tables and outputting as JSON format?

I currently have PostgreSQL set up with the following table structure: CREATE TABLE "objs"("number" Integer,"name" Text NOT NULL, "price" Text NOT NULL ); CREATE TABLE "users"("name" Text NOT NUL ...

The class WebTestCase was not found during the debug:autowiring check

After running php bin/console debug:autowiring, a series of errors were reported: In FileLoader.php line 168: Class Symfony\Bundle\FrameworkBundle\Test\WebTestCase not found in /vagrant/mysymfony/app/config/services.yml (whic h is ...

Tips for Effectively Adding Deciphered JSON Data into a Mysql Database

I have been struggling to figure out how to get my php code working with my database by searching online, but I'm having trouble understanding it all! That's why I decided to reach out and ask for help or guidance on this issue. Any assistance wo ...

Can divs trigger the `.resize` function?

Currently, I have a setup that looks like this: <div id="container"> <img src="" id="bigImg"> </div> Thumbnails are displayed on the page and when clicked, they change the content of #bigImg. My goal is to prevent the #container from ...

Update the designated dropdown menu using its identification number

I have discovered a way to change the selected dropdown item by value, but I am interested in doing it by the option ID instead. The reason for this is that the values are dynamically generated. Currently, I am working on creating a questionnaire that incl ...

Firefox fails to apply styling to content loaded through Ajax (particularly when using AngularJS)

I've encountered a strange problem while working on my app (MVC4 + AngularJS). It seems that in Firefox (currently version 42), content loaded through an Ajax call does not always pick up the CSS styles that were loaded before. In the attached images, ...

After loading ajax content onto the page, the scroll bars fail to appear

I am currently constructing a website that loads page content through ajax. Everything seems to be functioning perfectly, except for a peculiar issue I have encountered in Chrome and Safari. Surprisingly, it is working flawlessly in IE! The problem lies i ...

Evaluate if the database value matches the current value, then send the result through AJAX

I'm currently working on a web application that uses CodeIgniter to direct users to a jPlayer playlist after they complete a form submission. Recently, my client requested that I update the application to track the amount of time watched for each vid ...

What is the best way to retrieve a parameter from a URL?

How do I retrieve the value of access_token from a URL pattern like this: localhost/facebook/#access_token=xyz I've tried using $_GET['access_token'] but it doesn't seem to be working. Any suggestions on how I can successfully extract ...

jQuery Charset Grid

Currently, I am utilizing a jQuery Grid to present data written in Spanish. The data appears correctly with accents ( ´ ), but when attempting to search for data using accents, the server receives a corrupted string like ∫√ instead of the accented let ...

Performing a JSON RPC request using the getJSON method in jQuery

My attempt to send a json-rpc request to a remote server using the jquery getJSON method is not working as expected. Here is the code I am using: json_string=JSON.stringify(obj); var jqxhr = $.getJSON("https://91.199.226.106/ssljson.php?jsoncallback=?", j ...

Exploring the dynamic capabilities of JSON with ASP .Net

After successfully retrieving JSON data from a database using PHP through json_encode() and jQuery parsing, I'm curious if there is a similar method for accomplishing this dynamically in ASP.Net Web Forms. Specifically, without the need to pre-determi ...

Creating a collection by gathering data from interactive fields with the help of AngularJS

I have a project to create an attendance system for employees. The system requires me to track the attendance status of each employee by generating a dynamic form with text input fields and checkboxes using angularjs ng-repeat inside a table. This form wil ...