I am having a JSON file with the following values and I am trying to fill the DataTable with the values of the JSON file.
I would like the DataTable to be of the format with 3 columns (Color, Size, Quantity).
An example would be Red, Small, 100 and Red, Medium, 200.
However, these 3 columns are within the JSON object "invSelectionCount" as shown in my JSON file. How do I iterate through the JSON file to manipulate the object within it to fill up the DataTable?
AJAX Call
$.ajax({
'url': 'http://localhost:8080/Retail-war/webresources/products/getProduct/' + productId,
'method': 'GET',
'contentType': 'application/json; charset=utf-8',
'headers': {"Authorization": 'Bearer ' + sessionStorage.getItem('accessToken')},
}).done( function(data) {
$('#product-inventory-level').DataTable( {
"data": [data],
"columns": [
{ "data": "invSelectionCount"},
{ "data": "invSelectionCount"},
{ "data": "invSelectionCount"}
],
})
})
JSON File
{
"productId": 1,
"originalPrice": 59.9,
"currentPrice": null,
"productStatus": "LISTED",
"discount": null,
"productVol": null,
"invSelectionCount": {
"red=small": 100,
"red=medium": 200
},
}
You can use map on keys of invSelectionCount to return desired object
Object.keys(data["invSelectionCount"]).map(key =>{return {
Color: key.split('=')[0],
Size: key.split('=')[1],
Quantity: data["invSelectionCount"][key]
}})
Run this snippet
let data={
"productId": 1,
"originalPrice": 59.9,
"currentPrice": null,
"productStatus": "LISTED",
"discount": null,
"productVol": null,
"invSelectionCount": {
"red=small": 100,
"red=medium": 200 }
}
$('#product-inventory-level').DataTable({
"columns": [{
"title": "Color",
"data": "Color",
},
{
"title": "Size",
"data": "Size"
},
{
"title": "Quantity",
"data": "Quantity"
}
],
"data": Object.keys(data["invSelectionCount"]).map(key =>{return {
Color: key.split('=')[0],
Size: key.split('=')[1],
Quantity: data["invSelectionCount"][key]
}})
})
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css" >
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<table id="product-inventory-level"></table>
Try to expand this:
.done( function(data) {
var array = new Array();
Object.keys(json["invSelectionCount"]).forEach(function(key) {
var splitstring = key.split('=');
splitstring[0] -> red
splitstring[1] -> small
json["invSelectionCount"][key] -> 100
array.push({"color": splitstring[0], "size": splitstring[1], "quantity": json["invSelectionCount"][key],});
});
$('#product-inventory-level').DataTable( {
"data": [array],
"columns": [
{ "data": "color"},
{ "data": "size"},
{ "data": "quantity"}
],
})
})
Related
I am trying to implement ServerSide pagination using Datatable for AJAX POST request
here is my Javascript Code, if I use JSON.stringify for data field then api won't hit
$('#tripboard_table').DataTable({
proccessing: true,
serverSide: true,
ajax: {
"url": "http://localhost:5000/api/v1/trip/get-trip-list",
"contentType": "application/json; charset=utf-8",
"type": "POST",
"dataType": "json",
"data": {
"driver_id": "",
"franchise_id": login_data.franchise_id,
"page_no": 0,
"page_size": 10
}
},
columns: [
{ "data": "" },
{ "data": "reference_number" },
{ "data": "consignor_name" },
{ "data": "consignee_name" },
{ "data": "from_city" },
{ "data": "to_city" },
{ "data": "status" },
{ "data": "route_name" },
{ "data": "vehicle_number" },
{ "data": "driver_name" },
{ "data": "pickup_date" },
{ "data": "scheduled_delivery_date" },
{ "data": "total_money_allocated" },
{ "data": "total_money_released" }
]
});
if we remove JSON.stringify function from data and passed data as it is then api gets hit and showing error alert that
DataTables warning: table id=tripboard_table - Ajax error. For more
information about this error, please see http://datatables.net/tn/7
and no data is inserted in table.
In console it shows
Method Not Allowed
The method is not allowed for the requested URL.
Please suggest solution for this..
Use this for adding to existing request of data table
function (d) {
d.driver_id = "";
d.franchise_id = login_data.franchise_id;
d.page_no = 0;
d.page_size = 10;
return d;
}
https://datatables.net/manual/server-side#Sent-parameters
$('#tripboard_table').DataTable({
proccessing: true,
serverSide: true,
ajax: {
"url": "http://localhost:5000/api/v1/trip/get-trip-list",
"contentType": "application/json; charset=utf-8",
"type": "POST",
"dataType": "json",
"data": function (d) {
d.driver_id = "";
d.franchise_id = login_data.franchise_id;
d.page_no = 0;
d.page_size = 10;
return JSON.stringify(d)
});
}
},
columns: [
{ "data": "" },
{ "data": "reference_number" },
{ "data": "consignor_name" },
{ "data": "consignee_name" },
{ "data": "from_city" },
{ "data": "to_city" },
{ "data": "status" },
{ "data": "route_name" },
{ "data": "vehicle_number" },
{ "data": "driver_name" },
{ "data": "pickup_date" },
{ "data": "scheduled_delivery_date" },
{ "data": "total_money_allocated" },
{ "data": "total_money_released" }
]
});
I have and API endpoint in Zapier where I am calling all approved leave requests from a payroll system. as data.
const options = {
url: 'https://api.somepayroll.com/api/v1/leaves/requests',
method: 'GET',
headers: {
'Accept': 'application/json',
'Authorization': `Bearer ${bundle.authData.access_token}`,
'X-CLIENT-SECRET': bundle.authData.client_secret,
'X-CLIENT-ID': bundle.authData.client_id,
'X-STATUS': bundle.inputData.status
},
params: {
}
}
return z.request(options)
.then((response) => {
response.throwForStatus();
const results = z.JSON.parse(response.content);
// You can do any parsing you need for results here before returning them
return results.content;
});
That gets me the following response:
[
{
"employeeId": "1",
"requestId": 5487,
"hours": 8,
"leaveFromDate": "19-Feb-2020",
"leaveToDate": "19-Feb-2020",
"reason": "Birthday Party",
"status": "Pending",
"payElement": "Annual Leave",
"leaveBalanceType": {
"leaveType": "Annual",
"name": "Annual Leave",
"unit": "hours",
"organisationSpecific": false
},
"payElementId": 50,
"daysConsumed": 0,
"daysCurrent": 0,
"daysRemaining": 0,
"quantityConsumed": 0,
"quantityCurrent": 0,
"quantityRemaining": 8,
"additionalApprovalAcquired": false,
"leaveInDays": false,
"links": [
{
"rel": "self",
"href": "https://api.somepayroll.com/api/v1/leaves/requests/5487"
},
{
"rel": "employee",
"href": "https://api.somepayroll.com/api/v1/employees/1"
},
{
"rel": "payelement",
"href": "https://api.somepayroll.com/api/v1/payelements/AL"
}
],
"id": "5487"
},
{
"employeeId": "1",
"requestId": 5551,
"hours": 8,
"leaveFromDate": "23-Jan-2020",
"leaveToDate": "23-Jan-2020",
"reason": "Camping",
"status": "Pending",
"payElement": "Annual Leave",
"leaveBalanceType": {
"leaveType": "Annual",
"name": "Annual Leave",
"unit": "hours",
"organisationSpecific": false
},
"payElementId": 50,
"daysConsumed": 0,
"daysCurrent": 0,
"daysRemaining": 0,
"quantityConsumed": 0,
"quantityCurrent": 0,
"quantityRemaining": 8,
"additionalApprovalAcquired": false,
"leaveInDays": false,
"links": [
{
"rel": "self",
"href": "https://api.somepayroll.com/api/v1/leaves/requests/5551"
},
{
"rel": "employee",
"href": "https://api.somepayroll.com/api/v1/employees/1"
},
{
"rel": "payelement",
"href": "https://api.somepayroll.com/api/v1/payelements/AL"
}
],
"id": "5551"
}
]
What I am trying to do is also grab the name of the employee from the link in the response https://api.somepayroll.com/api/v1/employees/1 since it is only giving me the ID number. Is is possible to cross link data like that and match on employeeID and get the data called firstName to be part of this result?
it should handle by back-end however you can call link from response and get extra data,
I have this json response:
{
"tags": [
{
"name": "SolarData",
"results": [
{
"groups": [
{
"name": "type",
"type": "number"
}
],
"attributes": {
"customer": [
"Acme"
],
"host": [
"server1"
]
},
"values": [
[
1429950000000,
46,
3
],
[
1429960000000,
62,
3
],
[
1429970000000,
183,
3
],
[
1429980000000,
156,
3
],
[
1429990000000,
205,
3
]
]
}
],
"stats": {
"rawCount": 5
}
}
]
}
and I want to be able to only get the first two items of every value part of the item. Foe example I want to return [[1429950000000,46],[1429960000000,62],[1429970000000,183],.....] in a scope variable so I can eventually use it for a graph. I am new to angular and web dev in general but this is the way I've tried it so far.
$http({
url: 'file.json',
method: 'POST',
data: '(query data here)'
}).then(function(data, status){
$scope.solarData = data.tags.results.values;
conosle.log($scope.solarData);
});
You can use map:
var custom = data.tags[0].results[0].values.map(function(values) {
return [values[0], values[1]];
});
You can use slice if you want to return a lot of items or a variable number of them like
return values.slice(0, 2);
//---------------------^ replace this
var data = {
"tags": [{
"name": "SolarData",
"results": [{
"groups": [{
"name": "type",
"type": "number"
}],
"attributes": {
"customer": [
"Acme"
],
"host": [
"server1"
]
},
"values": [
[
1429950000000,
46,
3
],
[
1429960000000,
62,
3
],
[
1429970000000,
183,
3
],
[
1429980000000,
156,
3
],
[
1429990000000,
205,
3
]
]
}],
"stats": {
"rawCount": 5
}
}]
}
var custom = data.tags[0].results[0].values.map(function(values) {
return [values[0], values[1]];
});
console.log(custom);
var requirementArray = new Array();
for (i = 0; i < $scope.solarData.length ; i++) {
var pare = new Array();
pare.push($scope.solarData[i][0]);
pare.push($scope.solarData[i][1]);
requirementArray.push(pare);
}
requirementArray will be :
[[1429950000000,46],[1429960000000,62],[1429970000000,183],.....]
You can use Array.map for that:
$http({
url: 'file.json',
method: 'POST',
data: '(query data here)'
}).then(function(data, status){
$scope.solarData = data.tags[0].results[0].values.map(
function(curVal, index, arr) {
return [curVal[0], curVal[1]];
}
);
conosle.log($scope.solarData);
});
I'm trying to populate a Backbone collection from the JSON that spotify API return me. However, after I try populating the collection I'm getting this with a console.log() :
playlistSpotify child {length: 1, models: Array[1], _byId: Object}. But my collection should contain 3 objects (3 objects in the JSON returned).
Any ideas of what's going on?
JS:
Model :
module.exports = Backbone.Model.extend({
defaults: {
id: null,
selected : false,
name: null
},
initialize: function() {
}
});
Collection :
module.exports = Backbone.Collection.extend({
model : Playlist,
initialize: function() {
}
});
View (Just the function that load the JSON):
loadSpotifyPlaylists : function() {
var that = this;
$.ajax({
url: 'https://api.spotify.com/v1/users/'+ this.user.get('spotifyId') +'/playlists',
headers: {
'Authorization': 'Bearer ' + this.user.get('spotifyToken')
},
success: function(response) {
var playlistCollection = new Playlists2({ collection : JSON.stringify(response.items) });
var playlistView = new PlaylistSpotifyView({ collection : playlistCollection });
that.$playListsSpotify.append(playlistView.render().el);
}
});
},
The JSON Spotify return me (I volontary remove one item to make it shorter) :
{
"href": "https://api.spotify.com/v1/users/loco/playlists?offset=0&limit=20",
"items": [
{
"collaborative": false,
"external_urls": {
"spotify": "http://open.spotify.com/user/loco/playlist/6MpEay73SWJzyJHGu5u6bK"
},
"href": "https://api.spotify.com/v1/users/loco/playlists/6MpEay73SWJzyJHGu5u6bK",
"id": "6MpEay73SWJzyJHGu5u6bK",
"images": [
{
"height": 640,
"url": "https://mosaic.scdn.co/640/dc8743ffb149138cfe29334147b835532dbee0ddf3320826…dc7e917657c7982eab6ed5126307c6c3a67e1a3fb78245a8477312eeaec1621a2849969219",
"width": 640
},
{
"height": 300,
"url": "https://mosaic.scdn.co/300/dc8743ffb149138cfe29334147b835532dbee0ddf3320826…dc7e917657c7982eab6ed5126307c6c3a67e1a3fb78245a8477312eeaec1621a2849969219",
"width": 300
},
{
"height": 60,
"url": "https://mosaic.scdn.co/60/dc8743ffb149138cfe29334147b835532dbee0ddf33208261…dc7e917657c7982eab6ed5126307c6c3a67e1a3fb78245a8477312eeaec1621a2849969219",
"width": 60
}
],
"name": "quizz musical",
"owner": {
"external_urls": {
"spotify": "http://open.spotify.com/user/loco"
},
"href": "https://api.spotify.com/v1/users/loco",
"id": "loco",
"type": "user",
"uri": "spotify:user:loco"
},
"public": false,
"snapshot_id": "1OUgCAhN+ZsJo6whDez1kVA/R2DooVY4Rzw+Vij5HYHgz/PDFpjbUaiXz+fkapX7",
"tracks": {
"href": "https://api.spotify.com/v1/users/loco/playlists/6MpEay73SWJzyJHGu5u6bK/tracks",
"total": 64
},
"type": "playlist",
"uri": "spotify:user:loco:playlist:6MpEay73SWJzyJHGu5u6bK"
},
{
"collaborative": false,
"external_urls": {
"spotify": "http://open.spotify.com/user/loco/playlist/2KlAANyACpjJZmZfVGK0Mb"
},
"href": "https://api.spotify.com/v1/users/loco/playlists/2KlAANyACpjJZmZfVGK0Mb",
"id": "2KlAANyACpjJZmZfVGK0Mb",
"images": [
{
"height": 640,
"url": "https://i.scdn.co/image/24e6e9aac4ea49d92e260bb6875f4882c65c7f48",
"width": 640
}
],
"name": "Playlist2",
"owner": {
"external_urls": {
"spotify": "http://open.spotify.com/user/loco"
},
"href": "https://api.spotify.com/v1/users/loco",
"id": "loco",
"type": "user",
"uri": "spotify:user:loco"
},
"public": true,
"snapshot_id": "fqLltawhg+mMNV+nVEl5Rmj94uDI1kdbbzoZLPbs7uVtZclbYJqyEtIAvIacExVe",
"tracks": {
"href": "https://api.spotify.com/v1/users/loco/playlists/2KlAANyACpjJZmZfVGK0Mb/tracks",
"total": 1
},
"type": "playlist",
"uri": "spotify:user:loco:playlist:2KlAANyACpjJZmZfVGK0Mb"
}
],
"limit": 20,
"next": null,
"offset": 0,
"previous": null,
"total": 3
}
After some exploration I see this thing when I console.log the collection. I can't really understand what's happened.
Any help would be appreciated ! :)
You have a wrong creation of the instances. Change it to the next:
var playlistCollection = new Playlists2(response.items);
var playlistView = new PlaylistSpotifyView({ model : playlistCollection });
To initialize collection, you need just simply pass an array of objects as the argument to the constructor of collection
I'm having the following issue while using Flot for a graph. The input for the graph is JSON, retrieved from a server.
The ajax call to get the data is:
$.ajax({
url: 'graphdata.do',
dataType: 'json',
success: function (retData) {
renderGraph(retData);
}
});
And the renderGraph function:
function renderGraph(datasets)
{
var data = [];
console.log(datasets);
$('.cbScenarioSelected').each(function(index) {
if($(this).is(':checked')){
var id = $(this).prop("id"); //this works, right id is returned
data.push(datasets[id]);
}
});
$.plot($("#graph1"), data, {
yaxis: { min: 0 },
xaxis: { tickDecimals: 0 }
});
}
The data returned from the server:
{
"1": {
"label": "Name1",
"data": "[[133,64.8000030517578],[134,64.8099975585938],[135,65.0999984741211],[136,66.0699996948242],[137,66.129997253418],[138,66.2600021362305],[139,66.6699981689453],[140,66.9400024414063],[141,67.4100036621094],[142,68.0599975585938], [143,68.0800018310547],[144,68.3600006103516],[145,68.8699951171875], [146,69.4899978637695],[147,69.6500015258789],[148,70.0999984741211], [149,70.7400054931641],[150,70.9199981689453],[151,71.1500015258789], [152,71.7000045776367],[153,72.0899963378906],[154,72.4799957275391], [155,73.2700042724609],[156,73.3000030517578],[157,73.4599990844727], [158,73.5100021362305],[159,74.6799926757813],[160,77.5200042724609], [161,77.8399963378906],[162,78.8300018310547]]"
},
"2": {
"label": "Name2",
"data": "[]"
},
"3": {
"label": "Name3",
"data": "[]"
}
}
The graph container is shown, and so are the labels. The lines in the graph are not shown.
Anyone have an idea? I think it has something to do with the quotes around the "data" tag in the returned data, but I have no idea how to fix it.
In your JSON, data part are string because of they are encapsulated with quotes.
In fact, the json should look like (without quotes)
{
"1": {
"label": "Name1",
"data": [
[
133,
64.8000030517578
],
[
134,
64.8099975585938
],
[
135,
65.0999984741211
],
[
136,
66.0699996948242
],
[
137,
66.129997253418
],
...
]
},
"2": {
"label": "Name2",
"data": []
},
"3": {
"label": "Name3",
"data": []
}
}