eric
eric

Reputation: 320

Convert JSON String to Datatable using jQuery

see my script. why no data is displayed? I try many thing here https://datatables.net/manual/ajax#Data-array-location but i need help to display my json data to the datatable

$(document).ready(function() {

var json = '{"company_id":"1","company_name":"schneider"}';

    $('#example').DataTable( {
	    "data": JSON.parse(json),
        "columns": [
            { "data": "company_id" },
			{ "data": "company_name"}
        ]
    } );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>

<table id="example" class="display" style="width:100%">
	<thead>
		<tr>
			<th>C_ID</th>
			<th>C_NAME</th>
		</tr>
	</thead>
</table>

Upvotes: 3

Views: 7450

Answers (1)

Adrian
Adrian

Reputation: 8597

The data parameter accepts an array not an individual object.

You JSON should look like this:

var json = '[{"company_id":"1","company_name":"schneider"}]';

Here's a JSFiddle

Upvotes: 2

Related Questions