0

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?

2
  • I can't tell from your example whether you want to use a JavaScript data source, or an AJAX data source. You seem to be using a combination of the two. Which approach are you intending to use? Commented Jul 20, 2015 at 3:17
  • As well, your variable temporaryArraySectors isn't valid. An array must be enclosed in square '[' brackets. Edit: It appears that there was a copy paste error since it shows up OK in jsonString. Commented Jul 20, 2015 at 3:22

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

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.