Skip to content Skip to sidebar Skip to footer

How To Show Pictures In A Table Using JQuery DataTables

Is that possible that I can show my URL images in data-table? I returning my data in array as it shown here in my code and returning the URL image with... Before I knew the DataTab

Solution 1:

You can use columns.render option to define callback function to render cell content based on its data.

$('#example').DataTable({
    "ajax": {
        url: "/test/0",
    },
    "columns": [
        { "data": 0 },
        { 
          "data": 1,
          "orderable": false,
          "sortable": false,
          "render": function (data, type, row, meta){
             // If data will be displayed
             if(type === "display"){
                return '<img src="' + data + '">';

             // Otherwise, if search/filtering is performed
             } else {
                return data;  
             }
          }
        }
    ]
});

Note that if you use columns to define your columns, you must have an entry in the array for every single column that you have in your table (these can be null if you don't which to specify any options). Alternatively, you can use columnDefs to target specific columns.

See the example below for code and demonstration. Please note, that I'm using jQuery Mockjax plug-in just for the sake of demonstrating Ajax request, it's not needed for production code.

$(document).ready(function () {
   // AJAX emulation for demonstration only
   $.mockjax({
      url: '/test/0',
      responseTime: 200,
      responseText: {
         "data": [
            [ "100x150", "http://placehold.it/100x150" ],
            [ "200x150", "http://placehold.it/200x150" ],
            [ "300x150", "http://placehold.it/300x150" ]
         ]
      }
   });

   $('#example').DataTable({
       "ajax": {
           url: "/test/0",
       },
       "columns": [
           { "data": 0 },
           { 
             "data": 1,
             "orderable": false,
             "sortable": false,
             "render": function (data, type, row, meta){
                if(type === "display"){
                   return '<img src="' + data + '">';
                } else {
                   return data;  
                }
             }
           }
       ]
   });
});
<!DOCTYPE html>
<html>

<head>
  <meta charset="ISO-8859-1">

  <link href="//cdn.datatables.net/1.10.7/css/jquery.dataTables.min.css"  />
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  <script src="//cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js"></script>
  <script src="http://vitalets.github.com/x-editable/assets/mockjax/jquery.mockjax.js"></script>
  
</head>

<body>
  <table id="example" class="display" cellspacing="0" width="100%">
    <thead>
      <tr>
        <th>Name</th>
        <th>Picture</th>
      </tr>
    </thead>
  </table>

</body>

</html>

Post a Comment for "How To Show Pictures In A Table Using JQuery DataTables"