Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape markup in JSON-driven jQuery datatable?

I'm using a jquery datatable which is loading some JSON dynamically using the sAjaxSource property. Everything's fine, except that the loaded content is being treated as potential markup, so things go strange if text in cells contains < or somesuch.

How can I get datatables to escape my data before loading it into the table? I don't want to do it server side because the server shouldn't care what the client's going to do with the data.

like image 703
kdt Avatar asked Oct 12 '11 13:10

kdt


1 Answers

[note: the following answer is for DataTables 1.9x and below. 1.10 changed the method naming conventions and a few other things. 1.9x methods are available but deprecated and will inevitably be stripped out completely.]

If it's safe to strip them "wholesale" (ie. if you devise an escape string function that doesn't affect the JSON's validity), you can do it by using the fnServerData function:

"fnServerData": function ( sSource, aoData, fnCallback ) {
  $.ajax( {
    "dataType": 'json',
    "type": "GET",
    "url": sSource,
    "data": aoData,
    "success": function (data) {
      // run your escape string function to modify 'data'
      fnCallback(data); // or fnCallback(newData) if you used new variable
    }
  });
}

If you're not sure about the safety of modifying it wholesale, you can do it on a row-by-row basis with the fnRowCallback:

"fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {

  var cellData = myEscaper(aData[0]); // where myEscaper() is your own custom function
  $('td:eq(0)').text(cellData);

  return nRow;
}

In this sample, I'm only modifying the first cell. If it's applicable to all cells, you'll probably want to write an iterator that will go through the whole row to make the conversion. If it's only applicable to some cells, you can handle them one at a time.

Note that aData[0] and td:eq(0) only coincidentally have the same index (0). If you have any hidden columns, there will not necessarily be a match. Also, if you use mDataProp you will need to handle that as well.

like image 127
Greg Pettit Avatar answered Oct 25 '22 02:10

Greg Pettit