How to load json foriegn key data to jquery datatable - javascript

This is how my JSON data is getting using the url.
[
{
"id": 1,
"fullName": "Menushi",
"email": "menushi#gmail.com",
"contact": "04567383",
"department": {
"id": 1,
"departmentName": "Computing and Information System(CIS)",
"description": "This department is regarding computer science ",
"active": true
},
"imageUrl": "LCR438D8E9C68",
"active": true,
"file": null,
"address": "Polonnaruwa"
},
I want to display the department name in the Jsondata table.Below shows the part of the javascript file.Department object is in onetoone relationship.I want to display department object data also in the table.
$table.DataTable({
pageLength: 5,
lengthMenu: [[3, 5, 10, -1], ["3 Records", "5 Records", "10 Records", "All"]],
ajax: {
url: jsonUrl,
dataSrc: ''
},
columns: [
{
data : 'imageUrl',
mRender : function(data,type,row){
return '<img src="'+window.root+'/resources/images/'+data+'.jpg" class="dataTableImg">';
}
},
{
data: 'fullName'
},
{
data: 'address'
},
{
data: 'email'
},
{
data: 'department.departmentName',
},
{
data: 'contact'
}
I have used the above way to display the department name in my javascript file..But it display nothing.How I can over come this issue?

Related

HTML / JSON / Javascript / AJAX

i've tried to display some things from JSON into a localhost site ( "market_hash_name" and "image") but its only printing me one out of about 43 results on the site but in the console its printing all the elements.
i've used the " document.getElementById " to display it on the html site.
my question is:
Is there any kind of loop i can use to display all the market_hash_names and image on the html site?
<html>
<head>
<title>Inventory</title>
</head>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$.ajax({
url: 'inventory.json',
dataType: 'json',
type: 'get',
contentType: "text/html; charset=UTF-8",
cache: false,
success: function(data){
$(data.data.steam_inventory.items).each(function(index, value){
var marketname = value.market_hash_name
var urlicon = value.image
document.getElementById("outputIconURL").src = urlicon
document.getElementById("outputName").innerHTML = marketname
console.log(marketname, "\n", urlicon)
});
}
});
</script>
<img id=outputIconURL width="350" height="300">
<p id=outputName></p>
</body>
</html>
here is the JSON File but only 100 out of 4000 lines of code. should be enough.
{
"status": "success",
"data": {
"app_id": "730",
"context_id": "2",
"steam_inventory": {
"status": "success",
"fresh_or_cached": "cached",
"total_items": 45,
"items": [
{
"app_id": "730",
"context_id": "2",
"number_of_items": 2,
"item_ids": [
"20276818150",
"20224634211"
],
"asset_ids": [
"20276818150",
"20224634211"
],
"class_id": "3761545285",
"instance_id": "0",
"market_hash_name": "Prisma 2 Case",
"suggested_price": "0.03",
"item_type": "Container",
"item_class": null,
"item_rarity": null,
"item_weapon": null,
"item_quality": "Base Grade",
"item_itemset": "The Prisma 2 Collection",
"image": "https://steamcommunity-a.akamaihd.net/economy/image/-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXU5A1PIYQNqhpOSV-fRPasw8rsUFJ5KBFZv668FFU1nfbOIj8W7oWzkYLdlPOsMOmIk2kGscAj2erE99Sn2AGw_0M4NW2hIYOLMlhpcmY0CRM/256fx256f",
"inspectable": false,
"inspect_link": null,
"phase": null,
"tags": {
"type": "Container",
"collection": "The Prisma 2 Collection",
"category": "Normal",
"quality": "Base Grade"
},
"has_buy_orders": false,
"recent_sales_info": null,
"stickers": null,
"fraud_warnings": [
[],
[]
],
"is_listing_allowed": false
},
{
"app_id": "730",
"context_id": "2",
"number_of_items": 1,
"item_ids": [
"20276522620"
],
"asset_ids": [
"20276522620"
],
"class_id": "469444882",
"instance_id": "302028390",
"market_hash_name": "Tec-9 | Urban DDPAT (Field-Tested)",
"suggested_price": "0.04",
"item_type": "Pistol",
"item_class": null,
"item_rarity": null,
"item_weapon": "Tec-9",
"item_quality": "Consumer Grade",
"item_itemset": "The Bank Collection",
"image": "https://steamcommunity-a.akamaihd.net/economy/image/-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpoor-mcjhoyszMdS1D-OOjhoK0mvLwOq7c2D4B6pwijLiXpt6s3lDkrkJvZG-hLI7Ee1M7YVmC8gO-kunrjZK1tJXXiSw0uDynv1g/256fx256f",
"inspectable": true,
"inspect_link": "steam://rungame/730/76561202255233023/+csgo_econ_action_preview%20S76561198248775632A%asset_id%D7936680248821929362",
"phase": null,
"tags": {
"type": "Pistol",
"weapon": "Tec-9",
"collection": "The Bank Collection",
"category": "Normal",
"quality": "Consumer Grade",
"exterior": "Field-Tested"
},
"has_buy_orders": false,
"recent_sales_info": null,
"stickers": null,
"fraud_warnings": [
[]
],
"is_listing_allowed": false
},
{
"app_id": "730",
"context_id": "2",
"number_of_items": 1,
"item_ids": [
"20215185457"
],
"asset_ids": [
"20215185457"
],
"class_id": "4141779477",
"instance_id": "519977179",
"market_hash_name": "Desert Eagle | The Bronze (Factory New)",
"suggested_price": "0.34",
"item_type": "Pistol",
"item_class": null,
"item_rarity": null,
"item_weapon": "Desert Eagle",
"item_quality": "Industrial Grade",
"item_itemset": "The Control Collection",
"image": "https://steamcommunity-a.akamaihd.net/economy/image/-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgposr-kLAtl7PLFTjNX4d6zhpO0leX7PaHUqWdY781lxLCZo9yh3gW3_hJqNj_2Jo6TelI8NQmErlPsyLq90ZPvtJnLm3Ux6CA8pSGK8qELUuc/256fx256f",
"inspectable": true,
"inspect_link": "steam://rungame/730/76561202255233023/+csgo_econ_action_preview%20S76561198248775632A%asset_id%D16890227741044942403",
"phase": null,
"tags": {
"type": "Pistol",
"weapon": "Desert Eagle",
"collection": "The Control Collection",
"category": "Normal",
"quality": "Industrial Grade",
"exterior": "Factory New"
},
"has_buy_orders": false,
"recent_sales_info": {
"hours": "18.86",
"average_price": "0.27"
},
"stickers": null,
"fraud_warnings": [
[]
],
"is_listing_allowed": true
},
You are using innerHTML so your content is override and only last one display .Instead you can generate htmls in your each loop and append same to some div .
Demo Code :
var data = {
"status": "success",
"data": {
"steam_inventory": {
"items": [{
"market_hash_name": "Prisma 2 Case",
"image": "https://steamcommunity-a.akamaihd.net/economy/image/-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXU5A1PIYQNqhpOSV-fRPasw8rsUFJ5KBFZv668FFU1nfbOIj8W7oWzkYLdlPOsMOmIk2kGscAj2erE99Sn2AGw_0M4NW2hIYOLMlhpcmY0CRM/256fx256f",
},
{
"market_hash_name": "Tec-9 | Urban DDPAT (Field-Tested)",
"image": "https://steamcommunity-a.akamaihd.net/economy/image/-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpoor-mcjhoyszMdS1D-OOjhoK0mvLwOq7c2D4B6pwijLiXpt6s3lDkrkJvZG-hLI7Ee1M7YVmC8gO-kunrjZK1tJXXiSw0uDynv1g/256fx256f",
}
]
}
}
}
$(data.data.steam_inventory.items).each(function(index, value) {
var marketname = value.market_hash_name
var urlicon = value.image
//append datas
$("#result").append("<div><img class='outputIconURL' src='" + urlicon + "' width='350' height='300'><p class='outputName'>" + marketname + "</p></div>")
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="result">
<!--result will cme here--->
</div>

Ordering columns in JQuery DataTable -- when data is fed through Javascript

There are some forum questions similar to what I'm trying to do but I haven't been able to make it work.
We are pulling data into a DataTable through javascript. I'd like to set the data-order using a different column.
However, when I try the column is being interpreted as a string and not integer.
Here is what makes the table:
var securityTable = $('#security-table').DataTable({
"data": securitydata.guards,
"columns": [
{
"className": 'details-control',
"data": null,
"orderable": false,
//creates square for details row
"render": function (d) {
return '<i class="fa fa-plus-square" aria-hidden="true"></span>';
},
"defaultContent": ''
},
// is sorting by "sort" but is seeing numbers as alphebetical not numeric
{ "data": {
_: "date.display",
sort: "date.date_order"
} },
{ "data": "place" },
{ "data": {
_: "shot.display",
sort: "shot.shot_order"
} },
],
"paging": false,
"searching": false
});
This is what the data looks like:
var securitydata = {
"guards": [
{
"date": {
"display": "April 15, 2011",
"date_order": 1
},
"reported": "Yes",
"place": "Chicago, auto parts yard",
"shot": {
"display": "No one hit",
"shot_order": 24
},
"blurb": "A 52-year-old guard at an auto parts lot shot at a vehicle he said was coming toward him. The man inside the vehicle, accused of stealing equipment from the lot, drove away and was not reported injured.",
"link": ""
},
This is what we were using for help
Using the same example, but with sorthing
$(document).ready(function() {
$('#example').DataTable( {
order: [[ 2, "desc" ]],
ajax: "data/orthogonal.txt",
columns: [
{ data: "name" },
{ data: "position" },
{ data: "office" },
{ data: "extn" },
{ data: {
_: "start_date.display",
sort: "start_date.timestamp"
} },
{ data: "salary" }
]
} );
} );
Link to order here

ui-grid sort data after filter

I have this model containing labels in the user selected language.
"status": [{
"id": "IN_PROGRESS",
"label": "In progress"
}, {
"id": "KO",
"label": "Everything is KO"
}, {
"id": "OK",
"label": "Everything is OK"
}]
Data from server:
myService.data =[{
status:"OK",
history:"History 2"
},{
status:"IN_PROGRESS",
history:"History 3"
},{
status:"KO",
history:"History 4"
}
]
In my controller I have the following:
vm.myList = {
enableColumnMenus: false,
enableHorizontalScrollbar: 0,
enableVerticalScrollbar: 0,
enableRowSelection: false,
enableRowHeaderSelection: false,
multiSelect: false,
paginationPageSizes: [6],
paginationPageSize: 6,
useExternalSorting: false,
paginationTemplate: "views/templates/grid-custom-pager.html",
columnDefs: [{
displayName: "recording.status",
field: 'status',
headerCellFilter: 'translate',
cellFilter: 'translate',
sortCellFiltered: true,
cellTemplate: '<div class="ui-grid-cell-contents" translate-field="status" translate-value="COL_FIELD"></div>'
},
{
displayName: "recording.history",
field: 'history',
headerCellFilter: 'translate'
}],
data: myService.data}
When I press the header cell for sorting, the sort is made by the field value, not by the displayed value. Is there any way of sorting the column after the filtering is done?
Have you tried creating your own sorting algorithm? See the wiki page of the project Sorting in Ui-Grid

How to load Datatables from JSON object directly on Ajax success result?

After long time searching here around I can't find a solution to this problem, loading Datatables via Ajax GET is well documented but how can I use directly a JSON response after an Ajax POST?
This is my PHP function:
function getRelated() {
var elements = (document.getElementsByClassName('exashare'));
var query = [];
for(var i=0;typeof(elements[i])!='undefined';query.push(elements[i++].getAttribute('data-id')));
query = query.join(',');
$.ajax({
type: "POST",
url: baseUrl+"/requests/get_related.php",
data: "query="+query+'&_token='+_token,
cache: false,
success: function(html){
$('#example').DataTable( {
"processing": true,
"serverSide": true,
"ajax": {
'url':jQuery.parseJSON(html),
"dataSrc": ""
},
"columns" : [
{ "data": "#" },
{ "data": "id" },
{ "data": "art" },
{ "data": "name" },
{ "data": "title" },
{ "data": "tag" },
{ "data": "likes" },
{ "data": "views" },
{ "data": "duration" },
{ "data": "time" }
]
});
}
});
}
The JSON on success looks like this:
{
"data": [{
"#": "1",
"id": "9",
"art": "default\/def8.jpg",
"name": "Simon The Cat",
"title": "Riflessioni sulla vita",
"tag": "riflessioni,vita,",
"likes": "1",
"views": "1024",
"duration": "185",
"time": "2015-11-30 19:36:31"
}, {
"#": "2",
"id": "15",
"art": "default\/def2.jpg",
"name": "Simon The Cat",
"title": "Riflessioni sulla morte",
"tag": "riflessioni,morte,",
"likes": "1",
"views": "1003",
"duration": "185",
"time": "2015-11-14 12:06:21"
},
...]
}
I also tried this:
//from this:
$('#example').DataTable( {
"processing": true,
"serverSide": true,
"ajax": {
'url':jQuery.parseJSON(html),
"dataSrc": ""
},
...
//to this:
$('#example').DataTable( {
"ajax": jQuery.parseJSON(html),
...
But on console it always shows me the error "lenght of undefined".
I already tried to load data directly from a JSON file url
containing the same response here above and it works well.
How can I load JSON data on Ajax POST success results to populate my table?
Finally, after many tries, I found the solution that works with the latest Datatables release (1.10.13):
function getRelated() {
var elements = (document.getElementsByClassName('exashare'));
var query = [];
for(var i=0;typeof(elements[i])!='undefined';query.push(elements[i++].getAttribute('data-id')));
//parse as string
query = query.join(',');
$.ajax({
type: "POST",
url: baseUrl+"/requests/get_related.php",
data: "query="+query+'&_token='+_token,
cache: false,
success: function(html){
//html is a json_encode array so we need to parse it before using
var result = jQuery.parseJSON(html);
$('#example_ert').DataTable( {
//here is the solution
"data": result.data,
"ajax": {
"url": result,
"dataSrc": ""
},
"columns" : [
{ "data": "#" },
{ "data": "id" },
{ "data": "art" },
{ "data": "name" },
{ "data": "title" },
{ "data": "tag" },
{ "data": "likes" },
{ "data": "views" },
{ "data": "duration" },
{ "data": "time" }
]
});
}
});
}

JSGrid Not show data from json

Hi I'm tryng to modify the "DataManipulation" example from jsGrid demos and I'm not able to show data from a json file retrived using a GET ajax call. Here's my controller code:
{
loadData: function (filter) {
var data = $.Deferred();
$.ajax({
type: "GET",
contentType: "application/json",
url: "myFileURL.json",
dataType: "json"
}).done(function(response){
console.log(response);
data.resolve(response);
});
return data.promise();}
The json retrived is like this
{"98762":{"Address":"Address 1","Age":1,"Country":1,"Married":false,"Name":"Name1"},"637399":{"Address":"Address 2","Age":2,"Country":2,"Married":true,"Name":"Name 2"},"234567554":{"Address":"Address 3","Age":3,"Country":3,"Married":true,"Name":"Name"}}
Your json is not well formed. jsGrid expects a list of objects as a return type. Use this instead.
[
{
"Address": "Address 1",
"Age": 1,
"Country": 1,
"Married": false,
"Name": "Name1"
},
{
"Address": "Address 2",
"Age": 2,
"Country": 2,
"Married": true,
"Name": "Name 2"
},
{
"Address": "Address 3",
"Age": 3,
"Country": 3,
"Married": true,
"Name": "Name"
}
];
This is with the assumption that the schema of the json is correct. Good luck!

Categories