Javier Muñoz
Javier Muñoz

Reputation: 780

How to pass JavaScript data to jQuery DataTables

I'm very frustrated trying to insert and show a JSON within a table. I'm using jQuery DataTable to do it.

I have the following jQuery and HTML code but without success:

<table id="sectorsTable">
    <thead>
        <tr>
            <th><b>Numero</b></th>
            <th><b>Nombre</b></th>
        </tr>
    </thead>
    <tbody>
    </tbody>
</table>

<script>
var jsonArray = { layersSelected: temporaryArraySectors };
var jsonString = JSON.stringify(jsonArray, null, 2);

$('#sectorsTable').dataTable({ 
    'ajax': jsonString
});
</script>

By the way, the content of the vars is:

temporaryArraySectors = [ [19,"Cordillera"], [10,"Guaiquillo"], [34,"Zapallar"], [27,"Rural Poniente"], [1,"Aguas Negras"], [24,"La Obra"], [28,"Rural Sur"] ];
jsonString = '{"layersSelected": [ [19,"Cordillera"], [10,"Guaiquillo"], [34,"Zapallar"], [27,"Rural Poniente"], [1,"Aguas Negras"], [24,"La Obra"], [28,"Rural Sur"] ] }';

What is wrong?

Upvotes: 0

Views: 136

Answers (1)

Gyrocode.com
Gyrocode.com

Reputation: 58860

You don't need to create JSON string with JSON.stringify, just set data option equal to temporaryArraySectors.

See example below for code and demonstration.

$(document).ready(function() {

  var temporaryArraySectors = [ [19,"Cordillera"], [10,"Guaiquillo"], [34,"Zapallar"], [27,"Rural Poniente"], [1,"Aguas Negras"], [24,"La Obra"], [28,"Rural Sur"] ];
  
  var table = $('#sectorsTable').DataTable({
    data: temporaryArraySectors 
  });

});
<!DOCTYPE html>
<html>

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

  <link href="//cdn.datatables.net/1.10.7/css/jquery.dataTables.min.css" rel="stylesheet" />
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/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="sectorsTable" class="display">
     <thead>
         <tr>
             <th><b>Numero</b></th>
             <th><b>Nombre</b></th>
         </tr>
     </thead>
     <tbody>
     </tbody>
  </table>
</body>

</html>

Upvotes: 1

Related Questions