Formatting HTML Tags with Ajax data

Formatting HTML Tags with Ajax data

El_MatellaEl_Matella Posts: 12Questions: 6Answers: 0

Hi everyone,

I am a new member and a complete new user of this wonderful jQuery Plugin. But I am having some questions with HTML formatting when data is coming from Ajax Request.

So here is my databale code:

$('#Table').DataTable( {
    "ajax": 'myfile.json',
    "columns": [
        { "data": "id" },
        { "data": "ref" },
        { "data": "name" }
    ],
    "deferRender": true
});

And with that, my HTML is like:

<tr role="row" class="odd">
    <td class="">62</td>
    <td class="sorting_1">3000</td>
    <td class="">My Product</td>
</tr>

And I would like to modify the render and add data attributed to my td cells, like:

<tr role="row" class="odd">
    <td data-url="myurl" data-id="62" class="">62</td>
    <td data-url="myurl" data-id="62" class="sorting_1">3000</td>
    <td data-url="myurl" data-id="62" class="">My Product</td>
</tr>

So what I want a do would be a custom HTML template for Ajax rendering, is it possible?

Thanks in advance for your answers :)

This question has accepted answers - jump to:

Answers

  • jLinuxjLinux Posts: 981Questions: 73Answers: 75
    Answer ✓

    Sure, you can use the createdRow.

    I do have a suggestion for you though, instead of adding the same data attributes to every td, I would suggest adding the tags once to the tr, then just use some JS to get the data-id from the closest row:

    var $row    = $(this).closest('tr');
    var data_id = $row.data('id');
    

    Here is an example of both

    You can see that in createdRow I add a data-id tag to the entire row (the tr) as well as each cell.

    Then for the two on-click events at the bottom, I handle getting the data-id from the tr in the first column, then getting it from the td in the 2nd.

  • El_MatellaEl_Matella Posts: 12Questions: 6Answers: 0

    Looks exactly for what I was looking for, thanks a lot, and thank you for the suggestions, I am going to use it!

    Have a nice day :)

  • jLinuxjLinux Posts: 981Questions: 73Answers: 75
    Answer ✓

    Great! Those are the methods I use as well

This discussion has been closed.