I am trying to use dataSrc property or manipulation method for table data. To see how I can manipulate data, I am trying this simple code.
test.php
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/r/bs-3.3.5/jq-2.1.4,dt-1.10.8/datatables.min.css"/>
<script type="text/javascript" src="https://cdn.datatables.net/r/bs-3.3.5/jqc-1.11.3,dt-1.10.8/datatables.min.js"></script>
</head>
<body>
<br /><br />
<div class="container">
<table id="data-table" class="table table-bordered">
<thead>
<tr>
<th>Mobile</th>
<th>Name</th>
<th>Email</th>
<th>Credits</th>
</tr>
</thead>
</table>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('#data-table').DataTable({
"ajax" : {
"dataSrc": function ( json ) {
var array = {};
for ( var i=0, ien=json.length ; i<ien ; i++ ) {
array[i] = json[i];//'<a href="/message/'+json[i][0]+'>View message</a>';
}
console.log(json);
console.log(JSON.stringify(json));
return (JSON.stringify(json));
}
},
"columns" : [
{ "data" : "Mobile",
"defaultContent": "<i>Not set</i>"},
{ "data" : "Name",
"defaultContent": "<i>Not set</i>"},
{ "data" : "Email",
"defaultContent": "<i>Not set</i>"},
{ "data" : "Credits",
"defaultContent": "<i>Not set</i>"},
]
});
});
</script>
When I run, localhost/test.php
Mobile Name Email Credits
Not set Not set Not set Not set
Not set Not set Not set Not set
Not set Not set Not set Not set
Though, data.json has:
{
"data": [{
"Mobile": "1234567890",
"Name": "test",
"Email": "[email protected]",
"Credits": "50",
}, {
"Mobile": "8200469963",
"Name": "amit",
"Email": "[email protected]",
"Credits": "0",
}, {
"Mobile": "8989899889",
"Name": "sdfsd",
"Email": "sdfsd",
"Credits": "100",
}, {
"Mobile": "9889812580",
"Name": "box",
"Email": "[email protected]",
"Credits": "98",
}, {
"Mobile": "9999999999",
"Name": "user9",
"Email": "[email protected]",
"Credits": "0",
}]
}
Also, If I remove dataSrc part totally. I get Proper results. What am I doing wrong in dataSrc?
When you remove the dataSrc component you are setting it to read the data as an array. You're just not specifying the data object you need to use json.data instead of just json.
$('#data-table').dataTable( {
"ajax": {
"url": "data.json",
"dataSrc": function ( json ) {
for ( var i=0, ien=json.data.length ; i<ien ; i++ ) {
json.data[i][0] = '<a href="/message/'+json.data[i][0]+'>View message</a>';
}
return json.data;
}
}
} );
Hopefully that helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With