I try to send data to datatable in json file like bellow: exemple data of my json file:
"responseHeader":{
"status":0,
"QTime":2,
"params":{
"q":"vba",
"indent":"true",
"fl":"name,role_t,born,natio_t",
"wt":"json"}},
"response":{"numFound":7,"start":0,"docs":[
{
"name":"Khouli",
"born":["1978-04-03T00:00:00Z"],
"natio_t":"tunisien",
"role_t":"Consultant"},
{
"name":"Atayi",
"born":["1987-06-24T00:00:00Z"],
"natio_t":"Francaise",
"role_t":"Consultant"}
}
That is my function:
$ ( document ).ready(function() {
$.ajax({
type: 'GET',
url: '../search.json',
success: function(data) {
$.each(data, function(i, data) {
var body = "<tr>";
body += "<td>" + data.name + "</td>";
body += "<td>" + data.born + "</td>";
body += "<td>" + data.natio_t + "</td>";
body += "<td>" + data.role_t + "</td>";
body += "</tr>";
$('.datatable-ajax-source table').append(body);
});
But I get table with undifined value
how to get this value from json files
Your input data seems to be wrong: Corrected data here:
{
"responseHeader":{
"status":0,
"QTime":2,
"params":{
"q":"vba",
"indent":"true",
"fl":"name,role_t,born,natio_t",
"wt":"json"}},
"response":{"numFound":7,"start":0,"docs":[
{
"name":"Khouli",
"born":["1978-04-03T00:00:00Z"],
"natio_t":"tunisien",
"role_t":"Consultant"},
{
"name":"Atayi",
"born":["1987-06-24T00:00:00Z"],
"natio_t":"Francaise",
"role_t":"Consultant"}
]
}
}
The proper JS to handle this:
$(document).ready(function() {
$.ajax({
type: 'GET',
url: '../search.json',
success: function(data) {
// Data is the root node of your json response.
// You need to navigate through the "docs" node.
if(data.response.docs && data.response.docs.length > 0)
{
$.each(data.response.docs, function(i, item) {
var body = "<tr>";
body += "<td>" + item.name + "</td>";
body += "<td>" + item.born + "</td>";
body += "<td>" + item.natio_t + "</td>";
body += "<td>" + item.role_t + "</td>";
body += "</tr>";
$('.datatable-ajax-source table').append(body);
}
});
You are not getting the proper value for data
.
You should get the docs.data[i]
which is, in this case, item
as defined in the .each()
.