6

I'm using jQuery DataTables to display information from JSON encoded PHP response. The JSON response contains the object "name". "name" contains "Full Name", "Last Name", "ID". I have been using columns to display the data the way I want but, I've ran into a problem I can't figure out.

In the code below example 1 works fine and will display "Full Name" while sorting by "Last Name". However, example 2 is not working at all. The desired output would contain HTML rendered display and sorted by "Last Name". In example 3 the display is rendered the way I would like but it is not sorted correctly.

Does anyone know how to adjust example 2 to output what I am looking for (rendered and sorted data)?

var oTable = $('#table').DataTable({
'ajax': {
    url: 'PHP-file-returns-JSON.php',
    type: "POST",
    dataSrc: function ( data ) {
            return data.cols;
        },       
    data: function(d) {

       ///send additional values to POST
       var frm_data = $('#val1, #val2').serializeArray();
       $.each(frm_data, function(key, val) {
             d[val.name] = val.value;
       });
     }
},
'columns':[

        // exapmle 1 - works but not rendered with HTML
        { data: {
                _:    "name.Full Name",
                sort: "name.Last Name",
                } 
        },

        // example 2 not working at all
        { data: 'name', "render": function ( data, type, row ) {
                return '<span id="'+data.ID+'">'+data.Full Name+'</span>';
            },
            "sort" : "name.Last Name",
        },

        // example 3 works fine with HTML rendered display but not sorted
        { data: 'name', "render": function ( data, type, row ) {
                return '<span id="'+data.ID+'">'+data.Full Name+'</span>';
            } 
        },
]
});

UPDATE:

HERE is the JSFiddle that shows the data structure I'm working with. The working example only shows the Full Name sorted by the Last Name. I am trying to figure out how to make the display contain a span element with the ID as the id attribute.

3
  • from all examples i found the problem is that to allow order of datatables they dont create any extra tag into the cell, so why do you try to just add the id to the td and dont use the span?, with your example 1 Commented Feb 1, 2017 at 14:39
  • Could you work up a simple JSFiddle to illustrate your use case please? Does your table have 3 columns, for instance? You can mock the ajax return by just using a simple JSON object as your data source. Commented Feb 1, 2017 at 18:19
  • @annoyingmouse I'm not sure how to set up a JSON response with JSFiddle. However, my code sample should only display one column containing the full name rendered as HTML. I just showed the 3 examples so people can get a better idea of what i'm trying to do. Commented Feb 1, 2017 at 20:22

4 Answers 4

11

Turns out that using name.Full Name will not work. It has to be name.FullName without the space. Here is what ended up working for me.

  'columns': [
        { 
            "data": "name",                   
            "render": function ( data, type, row ) {
                if(type === 'display'){
                    return '<span id="'+data.ID+'">'+data.FullName+'</span>';
                }else if(type === 'sort'){
                    return data.LastName;
                }else{
                    return data;
                }
            }
        }
   ]
Sign up to request clarification or add additional context in comments.

Comments

1

If you need to sort the column on the last name this should work:

$.extend($.fn.dataTableExt.oSort, {
  "last-name-pre": function(a) {
    return $(a).data("lastname");
  },
  "last-name-asc": function(a, b) {
    return ((a < b) ? -1 : ((a > b) ? 1 : 0));
  },
  "last-name-desc": function(a, b) {
    return ((a < b) ? 1 : ((a > b) ? -1 : 0));
  }
});


$("#example").DataTable({
  "data": data,
  "columns": [{
    "title": "Full Name",
    "data": "Full Name",
    "render": function(data, type, row) {
      return $("<span></span>", {
        "text": data,
        "data-lastname": row["Last Name"]
      }).prop("outerHTML");
    },
    "type": 'last-name'
  }]
});

It's working here. You could also remove the render function and just adapt the last-name function to split the full name and return the last name:

$.extend($.fn.dataTableExt.oSort, {
  "last-name-pre": function(a) {
    return a.split(" ")[1];
  },
  "last-name-asc": function(a, b) {
    return ((a < b) ? -1 : ((a > b) ? 1 : 0));
  },
  "last-name-desc": function(a, b) {
    return ((a < b) ? 1 : ((a > b) ? -1 : 0));
  }
});


$("#example").DataTable({
  "data": data,
  "columns": [{
    "title": "Full Name",
    "data": "Full Name",
    "type": 'last-name'
  }]
});

Which is here. Hope that helps, and that I've understood your requirements properly.

3 Comments

I added an example of the data structure I'm working with. I tried using your code but I couldn't get it to work.
"data" only lets me use Full Name. It won't let me add any HTML formatting. I'm looking for the display to render as: <span id="'+ID+"'>'+Full Name+'</span>'
Try again, updated the JSFiddle to output the correct span. Hope that helps.
1
enter code herefunction Display() {
    $('#xyz').dataTable({
         "bServerSide": true,
            "bSort": false,
           "sAjaxSource": ,
            "lengthMenu": [10, 25, 50, 100],
            "iDisplayLength": 10,
            "bDestroy": true,
            "bFilter": true,
            "bPaginate": true,
            "bInfo": true,
            "sSearch": true,
            "bLengthChange": true,
            "sEmptyTable": "Loading data from server",
            "fnServerData": function (sSource, aoData, fnCallback) {
                $.ajax({
                    "dataType": 'json',
                    "type": "POST",
                    "url": sSource,
                    "data": aoData,
                    "success": fnCallback
                });
            },
            "columns": [
                {
                    "sWidth": "0.5%",
                    "render": function (data, type, row, meta) {
                        return '<a href="javascript:void(0);" User_ID="' + row[0] + 
                            '" Otp_Mobile="' + row[11] + '" IsActive="' + row[12] +

                            '"  onclick="GetEdit(this);"><i class="glyphicon glyphicon-edit"></i></a>';
                    }, "targets": 0
                },

                {
                    "sWidth": "0.5%",
                    "render": function (data, type, row, meta) {
                        return '<a href="javascript:void(0);" onclick="DeleteData(' + row[0] + ')"><i class="glyphicon glyphicon-trash"></i></a>';
                    }, "targets": 0
                },
                {
                    "sWidth": "2%",
                    "render": function (data, type, row) {
                      return row[2];
                    }
                },

                {
                    "sWidth": "2%",
                    "render": function (data, type, row) {
                        return row[1];
                    }
                },
                {
                    "sWidth": "2%",
                    "render": function (data, type, row) {
                        return row[5];
                    }
                },
                {
                    "sWidth": "2%",
                    "render": function (data, type, row) {
                        return row[7];
                    }
                },
                {
                    "sWidth": "2%",
                    "render": function (data, type, row) {
                        return row[12];
                    }
                },

            ],
     });
  }

Comments

0

You can try this :

{
    data: null,
    title: "Audio",
    render: function (data) {
    return `<a onclick="UpdateRecord('${data.audio_status_id_string}','${"Audio"}','${data.request_id}')">${AudioStatusColor(data.audio_status_id_string)}</a>`
                           }
                       },

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.