How to insert nested json in Datatables javascript - javascript

In response from controller in ajax I'm getting a string array, which I m converting to javascript array
The problem is that the array contains a nested json array
which I need to plot on jquery DataTables.
For normal Jsons it is working but if the Json is nested it is not working.
How to to implement this?
What I'm trying to do is
making a array of data and title and pushing that array to columns of DataTables
But this only works for normal json
but not for nested json array.
This is my nested Json Example:-
//SAMPLE JSON { "id": "1951-4", "example": { "1": [ 6721 ], "2": [ 6722 ] } }
Need to represent DataTable of the above sample json Object..
$.ajax({
url: "/api/searchData/",
type: "POST",
dataType: "text",
beforeSend: function () {
$("#resultLoader").show();
},
success: function (result) {
var resultArray = JSON.parse(result);
var my_columns = [];
var my_item = {};
var nestedcolumns = [];
$.each(resultArray[0], function (key, value) {
var my_item = {};
if (typeof value === "object") {
$.each(value, function (key, value) {
var nestedItem = {};
nestedItem.data = key;
nestedItem.title = key;
nestedcolumns.push(nestedItem);
my_item.data = nestedcolumns;
});
} else {
my_item.data = key;
}
my_item.title = key;
my_columns.push(my_item);
});
$("#example").show();
var table = $('#example').DataTable({
data: resultArray,
"columns": my_columns
});
},
complete: function () {
$("#resultLoader").hide();
},
error: function (error) {
console.log("Error", error);
}
});
Error:
DataTables warning: table id=example - Requested unknown parameter
'[object Object],[object Object]' for row 0, column 1. For more
information about this error, please see http://datatables.net/tn/4

Related

javascript to filter json and return another value

I have some javascript:
datasetID is set from the url value.
I get the json data.
const datasetID = urlParams.get('datasetID')
var data;
$.getJSON("json/data.json", function(json){
data = json;
});
Next I want to filter the json data based on the datasetID, then retrieve the value assigned to another attribute vernacularName and assign it to a const.
const record = data.filter(d => d.datasetID === datasetID);
const vernacularName =
How far away am I? Suggestions welcome.
sample code
[
{
"datasetID":"A1"
"language":"en",
"accessRights":"CC BY 4.0",
"vernacularName":"goat"
}
]
Filter in front-end is not a good option (let say your data.json is large) so if you could filter it in back-end before retrieving. For example, I send an ajax request with parameter ID: datasetID :
const datasetID = urlParams.get('datasetID')
var data;
$.ajax({
type: "POST",
url: "/getjson",
dataType: "json",
success: function (json) {
record = json
if (record.length === 1)
vernacularName = record[0]["vernacularName"]
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log('error');
},
data: {
ID: datasetID
},
cache: false
})
If you can't tweak in back-end and datasetID is unique then this should be enough:
if (record.length === 1)
vernacularName = record[0]["vernacularName"]

Iterating over JSON Data on AJAX Success Using JQuery

I have an AJAX call that return JSON data from a query:
<script>
function retrieveTrips(){
// Get a history of trips
$.ajax({
url:'cfcs/mileagedata.cfc?method=getTrips&returnformat=json',
data: { ticket_id: #get_ticket.ticket_id# },
success: function(response) {
$("##tripDate").html(response);
console.log(response);
}
});
}
</script>
I would like to iterate over the returned JSON data on the success function and output it to an HTML table using JQUERY. The closest I can come to this is just outputting all the data to a div in my table. Can anyone give me a hand on how that JQUERY code would look?
Here is my JSON response:
{
"COLUMNS": ["ID", "VEHICLE_ID", "TICKET_ID", "_DATE", "START_ODOMETER", "END_ODOMETER", "ORIGIN", "DESTINATION", "TOTAL_MILEAGE", "EXPENSES", "DESCRIPTION"],
"DATA": [
[1650, "6", "30996", "September, 29 2016 00:00:00 -0400", "11782", "11822", "Jaydien", "Mazza", "40", "0.00", ""]
]
}
MY EDITS:
<script>
function retrieveTrips(){
// Get a history of trips
$.ajax({
url:'cfcs/mileagedata.cfc?method=getTrips&returnformat=json',
data: { ticket_id: #get_ticket.ticket_id# },
success: function(response) {
$("##tripDate").html(response);
for (i = 0; i < response.DATA.length; i++) {
var row = response.DATA[i];
console.log(row);
}
}
});
}
</script>
Try this in your success call, place this instead of your console.log();
response = JSON.parse(response);
for (i = 0; i < response.DATA.length; i++) {
var row = response.DATA[i];
console.log(row);
}
Also you have a ## which should be just 1 # or else it wont return to the propper element
The return json is a JSON returned with two properties both containing an Array the first property tell you what the columns mean the second one contains the actual data, to approach only the data you call response.DATA, DATA is the property name in the json object

jQuery autocomplete for json data

I am returning array of strings from controller to ajax call. trying to set to textbox those values. in textbox it is not populating. but I can see data in success method.
[HttpGet]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public JsonResult GetWorkNamesAutoPoplate(string companyName)
{
...
var newKeys = companyNameslst.Select(x => new string[] { x }).ToArray();
var json = JsonConvert.SerializeObject(newKeys);
return Json(json, JsonRequestBehavior.AllowGet);
}
JS
$(document).on('change', '[name="FindCompanyName"]', function () {
$('[name="FindCompanyName"]').autocomplete({
source: function (request, response) {
$.ajax({
url: "GetWorkNamesAutoPoplate",
type: "GET",
dataType: "json",
data: { companyName: $('[name="FindCompanyName"]').val() },
success: function (data) {
alert(JSON.stringify(data));
response($.map(data, function(item) {
console.log(item);
return {
value: item
}
}));
}
});
},
messages: {
noResults: "", results: ""
}
});
});
alert(JSON.stringify(data)); display like this.
How to populate this data in textbox
The return type of your json is an array of arrays, i think you should return it as an array
var newKeys = companyNameslst.ToArray();
also, your data are serialized twice,
one from line,
var json = JsonConvert.SerializeObject(newKeys);
and second time from JsonResult action filter
return Json(json, JsonRequestBehavior.AllowGet);
sending json data like,
return Json(newKeys, JsonRequestBehavior.AllowGet);
instead of
var json = JsonConvert.SerializeObject(newKeys);
return Json(json, JsonRequestBehavior.AllowGet);
should work.
hope this helps.
This may resolve your issue :
success: function (data) {
alert(JSON.stringify(data));
if (data != null) {
response(data.d);
}
}
Also this link might help you to get some information :How to use source: function()... and AJAX in JQuery UI autocomplete

Parsing an array posted to nodejs server using querystring

I always use querystring to parse data posted by client. But this is the first time I am posting an array, and I'm having same issue.
client side:
$.ajax({
url: 'myurl',
type: "POST",
data: {ids: ["str1","str2","str3"]},
success: function (msg) {
location.reload();
},
error: function (msg) {
alert("ServerError");
},
cache: false,
});
server side:
var body='';
req.on('data', function(chunk) {
body += chunk.toString();
});
req.on('end', function() {
var parsedbody = querystring.parse(body);
console.log(parsedbody);// {'ids[]':["str1","str2","str3"]}
My problem? Well, first note the comment: the key is ids[] intead of simply ids. So strange and annoyng. And the big problem: if I pass an array with one string like this:
data of ajax request--> data: { ids: ["str1"] }
the console.log becomes
console.log(parsedbody);// {'ids[]':"str1"}
console.log(parsedbody['ids[]'].length);// 4 (instead of 1)
As you can see my array become a string and this is a problem.
You could just easily create your own wrapper around querystring.parse(). Example:
var qs = require('querystring');
function parseQS(str) {
var result = qs.parse(str),
keys = Object.keys(result);
for (var i = 0, len = keys.length, key, newKey; i < len; ++i) {
key = keys[i];
if (key.slice(-2) === '[]') {
newKey = key.slice(0, -2);
if (!Array.isArray(result[key]))
result[newKey] = [ result[key] ];
else
result[newKey] = result[key];
delete result[key];
}
}
return result;
}
console.dir(parseQS('foo[]=bar&baz=bla&quux[]=123&quux[]=456'));
// outputs:
// { baz: 'bla',
// foo: [ 'bar' ],
// quux: [ '123', '456' ] }

Setting a variable inside a function in JS

var last = 0;
function grabProducts(searchstring) {
var last = 0;
$.post('ajax/products', {
method: 'search',
string: searchstring,
category: $('#search_category').val(),
sort: $('.sort').val()
}, function (data) {
data = $.parseJSON(data);
$.each(data, function (index, b) {
last = "dada";
});
});
}
alert(last);
Gives me alert with "0". How can i make it set the variable to "dada"?
You can't make a setup like that work because $.post() is asynchronous. You'll have to put the "alert" in the callback function you pass to $.post().
var last=0;
function grabProducts(searchstring) {
var last=0;
$.post('ajax/products', { method: 'search', string: searchstring, category: $('#search_category').val(), sort: $('.sort').val() }, function(data) {
data = $.parseJSON(data);
$.each(data, function(index, b) {
last = "dada";
});
alert(last);
});
}
The whole point of the callback, in fact, is to provide you with a way to have code run when the HTTP request is complete.
When you POST something, It needs time for server to respond. Do this:
var last=0;
function grabProducts(searchstring) {
var last=0;
$.post('ajax/products', { method: 'search', string: searchstring, category: $('#search_category').val(), sort: $('.sort').val() }, function(data) {
data = $.parseJSON(data);
$.each(data, function(index, b) {
last = "dada";
});
alert(last);
});
}

Categories

Resources