Del Del - 1 year ago 68
jQuery Question

DataTables Clickable Row Links from Server Side JSON

I have a datatable where I had been loading all the data at once, but my dataset is going to end up being very large so I decided to move everything server side.

Previously I was able to embed links into each row by using a "data-url" attribute then listening for a click with this function:

$('#table tbody').on('click', 'tr', function () {
var url = this.getAttribute("data-url"), "_self");

It worked perfectly like that, but I haven't been able to figure out how to make this work using AJAX and JSON.

My JSON response looks like this:

{"recordsFiltered": 1, "recordsTotal": 6,
"data": [{"4": "", "6": "", "7": "Online", "3": "", "DT_RowClass": "success",
"5": "", "data-url": "/relative-url/pk/", "2": "TestType2",
"0": "Test", "1": "ABCD"}], "draw": "11"}

However I'm not sure how I get DataTables to add the data-url attribute to the row. I've been scouring the documentation to try to find an example of this use case, but haven't had any luck so far.

If there isn't a built in functionality, I imagine that I will need to override the function DataTables uses to load in the JSON data, but I'm not sure how to do that.

I'm much better with my server side language than javascript so I really appreciate more specific answers if possible.

Thank you

Answer Source

As noted by @cjungel above that's one way to do it. Mor recent versions of DataTable use rowCallback though. So for example you could use this type of thing:

"rowCallback": function(row, data, index){
    $(row).attr("data-url", data[1]);

As per this JSFiddle. Hope that helps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download