Javascript JSON data with DataTables - javascript

I am using a JavaScript with jQuery DataTables but I have been having problem in loading the JSON data into the Bootstrap table.
This is a sample of the table
[ { name: 'Bryant Stone', hobbies: 'Football', favorite_team: 'Sea hawks', height: '5 Feet 10 in' },
{ name: 'Jesse Smith', hobbies: 'boxing', favorite_team: 'Spurs', height: '6 feet 6 in' },
{ name: 'Emily Wyclef', hobbies: 'cooking', favorite_team: 'Venus Williams', height: '5 feet 2 in' }
]
In JavaScript I get the data in this format and put it inside JavaScript like this
$(document).ready(function(){
$(\'#respondent\').dataTable({
destroy: true,
data: jsonStr1,
columns:[
{title:"Name", data: "name"},
{title:"Hobbies", data: "hobbies"},
{title:"Favorite team" ,data: "favorite_team"},
{title: "Height" ,data: "height"}
]
});
})
When I load the page it shows my data in the console but a DataTables dialog box shows this message
DataTable warning table id=respondent-
Requested unknown parameter 'name' for
row0, column 0. For information more.....
I don't know what else I can do. It has taken the whole day from me. Any help would be appreciated.
UPDATE
Thanks to all who helped by providing some answers all of which i have done.
This is my html
<table class="display" id="respondent">
<thead>
<tr>
<th>Name</th>
<th>Hobbies</th>
<th>Favorite Team</th>
<th>Height</th>
</tr>
</thead>
</table>
I have made needed typo correction to the code displayed earlier
but I still keep on getting this error message
DataTables warning: table id=respondent-
Requested unknown parameter 'name' for
row 0, column 0, for more information about this
error, please see http://datatables.net/tn/4
I went to the link but could not get anything helpful.
After the above message, the table get filled up with empty spaces
and after going to some pages I see just one character in the first
cell only. Those characters either letter or braces I do not know where
they came from because I could not see such sequence in my json data even
numbers shows up.
It keeps on baffling me I do not know what else to do.
Any help would be appreciated.
UPDATE
I discovered that the problem was that the data was in a string.
Does anyone know how to convert string in javascript to object without using eval(). JSON.parse return string and not object which is what is being looked for.

Minor changes:
, missing after data option
Column is passed as favourite_team (British english) but data has favorite_team (American English)
Column contains hobbies where as data contains hobbies in the first row while hobbie in the other rows. You gotta match them.
Use title option in the columns to show the header name
Info: That error/alert is usually due to missing columns in the data.
Here's a code snippet fixing the above:
$(document).ready(function(){
var jsonStr1 = [ { name: 'Bryant Stone', hobbies: 'Football', favorite_team: 'Sea hawks', height: '5 Feet 10 in' },
{ name: 'Jesse Smith', hobbies: 'boxing', favorite_team: 'Spurs', height: '6 feet 6 in' },
{ name: 'Emily Wyclef', hobbies: 'cooking', favorite_team: 'Venus Williams', height: '5 feet 2 in' }
];
$('#respondent').dataTable({
destroy: true,
data: jsonStr1,
columns:[
{title: "name", data: "name"},
{title: "hobbies", data: "hobbies"},
{title: "favorite_team", data: "favorite_team"},
{title: "height", data: "height"}
]
});
})
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.10.18/datatables.min.css"/>
<script src="//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<table id="respondent" class="display">
<thead>
</thead>
<tbody>
</tbody>
</table>
Hope this helps.

Typo errors of column names - hobbies are mentioned as "hobbie" and favourite_team as favorite_team.
Maintain same property names for all objects to avoid that error
Code sample for reference - https://codepen.io/nagasai/pen/vzNXPe
HTML:
<table class="display" id="respondent">
<thead>
<tr>
<th>Name</th>
<th>Hobbies</th>
<th>Favorite Team</th>
<th>Height</th>
</tr>
</thead>
</table>
JS
var jsonStr1 = [ { name: 'Bryant Stone', hobbies: 'Football', favorite_team: 'Sea hawks', height: '5 Feet 10 in' },
{ name: 'Jesse Smith', hobbies: 'boxing', favorite_team: 'Spurs', height: '6 feet 6 in' },
{ name: 'Emily Wyclef', hobbies: 'cooking', favorite_team: 'Venus Williams', height: '5 feet 2 in' }
]
$(document).ready(function() {
$('#respondent').dataTable({
destroy: true,
data: jsonStr1,
columns:[
{title:"Name", data: "name"},
{title:"Hobbies", data: "hobbies"},
{title:"Favorite team" ,data: "favorite_team"},
{title: "Height" ,data: "height"}
]
});
} );

Related

Format exponential number in table header with vuetify

I want to replace the header 'number' by a custom header made in html.
I use vuetify for display data table.
actually I have :
headers: [
{text: 'number', value: 'number'},
{text: 'car', value: 'car'},
{text: 'Total ', value: 'total'},
{text: 'Actions', value: 'actions'}
],
I think, I must play with the template and slot but I'm totaly lost.
I found the solution
<template v-slot:header.number>
Here My custom header
</template>
that's works great !

In my code i am tring to loop thorugh an object. Would this Vue js code be considered "AntiPattern"?

I'm new to Vue js and want to see if this proper coding practice. I am using v-for to loop through the objects but am not sure if this an antipattern. The first object is what i'd like to use to build the header colum. The next object(s) would be the item information. To clarify i am not sure if looping through an object this way is bad practice. I am looping through the first item to use the values as an index so that i can create rows for property in each object.
<thead>
<tr >
<th v-for="comparison in cartComparisons" class="flex-1 bg-gray-200 border-b border-white">
<a v-if="comparison.model.link" :href="comparison.model.link | ''">
{{comparison.model.name}}
</a>
<template v-else>{{comparison.model.name}}</template >
</th>
</tr>
</thead>
<tbody >
<template v-for='(comparison,key,index) in cartComparisons[0]'>
<tr v-if="index !== 0">
<td v-for="comparison in cartComparisons">
{{comparison[key]}}
</td>
</tr>
</template>
</tbody>
<script>
export default{
props:{
product: Object,
},
data () {
return {
cartComparisons: [
{
model: {
name: "Model",
},
price: 'Our Price',
frame: 'Frame',
frameTreatment: 'Frame Treatment',
loadCapacity: 'Load Capacity',
folding: 'Folding',
wheels: 'Wheels',
straps: 'Straps',
kickstand: 'Kickstand',
padding: 'Padding',
hardware: 'Hardware',
storageBag: 'Storage Bag',
},
{
model: {
name: "bike",
},
price: "$45.95",
frame: "Aluminum",
frameTreatment: "Treated",
loadCapacity: "65lbs",
folding: "Yes",
wheels: '7"',
straps: "3 Included",
kickstand: "Single Leg",
padding: "Rubber",
hardware: "Stainless Steel",
storageBag: "Bag included",
},
],
};
},
};
</script>

table in Angular using dynamic table headers

I was creating an angular app to display data from various data sources. I configured the list of various data sources in a JSON file each data source has a set of values attached to it.
Here is an example
var configurableConfigurations=[
{
name:"Locations",
table:"location_set",
columnList:[
{
name:"LOCATION_NAME",
alias:"Location",
primary:true
},
{
name:"DESCRIPTION",
alias:"Description",
primary:false
}
]
},
{
name:"System Parameters",
table:"system_params",
columnList:[
{
name:"param_Key",
alias:"Parameter",
primary:true
},
{
name:"param_Value",
alias:"Value",
primary:false
}
]
}
];
I then created an HTML page to display this using angular : the page has 2 parts
1. A select box which shows various parameters this is done using ng-repeat
<select name="ConfigurationName" ng-model="selected" ng-options="eachConfiguration.name for eachConfiguration in configurableConfigurations" ng-change="fetchRequiredConfiguration()">
A table which I want to generate using the headers of the parameter selected
this is my code to do that
<table id="configtable">
<thead>
<tr>
<th class="col-md-1" ng-repeat="column in selected.columnList" >{{column.alias}}</th>
</tr>
</thead>
This works great for the first time. But when the option is selected again using the select box the table header is not shown.
The table data is being populated properly , its just the table headers that are getting messed up.
Could anyone please help me get around this problem. I am new to angularjs. May be I am missing something important.
Edit ::
I should Also Mention that I fetch the data from the API and then was using the Data table plugin(https://www.datatables.net/download/) to show this as Data
$("#configtable").DataTable({
"ajax": "../fetchvalue/config/"+this.selected.table,
destroy: true,
"columns":{ "data": "ColumnXXX"},
{"data": "ColumnYYY" }
});
As it turns out, I have a problem with the disappearing headers only when I use the DataTable
I don't know how the table data is store but this way is good:
$scope.configurableConfigurations = [{
name: "Locations",
table: "location_set",
columnList: [{
name: "LOCATION_NAME",
alias: "Location",
primary: true
}, {
name: "DESCRIPTION",
alias: "Description",
primary: false
}],
data:[[12,"home"],[43,"work"]]
}, {
name: "System Parameters",
table: "system_params",
columnList: [{
name: "param_Key",
alias: "Parameter",
primary: true
}, {
name: "param_Value",
alias: "Value",
primary: false
}],
data:[["GOO",586],["FOO",123]]
}];
And then you can print the table like this:
<select name="ConfigurationName" ng-model="selected" ng-options="eachConfiguration as eachConfiguration.name for eachConfiguration in configurableConfigurations" ng-change="fetchRequiredConfiguration()"></select>
<table id="configtable">
<thead>
<tr>
<th class="col-md-1" ng-repeat="column in selected.columnList">{{column.alias}}</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="row in selected.data" >
<td class="col-md-1" ng-repeat="col in row">{{col}}</td>
</tr>
</tbody>
</table>
Example here

Having trouble refreshing Gridx using JsonRest

When an account is chosen, I would like to show all related contacts in contactGrid.
I can do this with XhrGet, but I would like to be using JsonRest.
Here is how I setup the Grid:
function contactTabSetup() {
var structure = [{ field: 'id', name: 'Id', width: '5em' },
{ field: 'firstName', name: 'First Name', width: '12%' },
{ field: 'lastName', name: 'Last Name', width: '12%' },
{ field: 'email', name: 'Email', width: '12%' },
{ field: 'description', name: 'Description' },
{ field: 'mobileNumber', name: 'Mobile Phone', width: '12%' }];
var contactGrid = new Grid({
id: 'contactGrid',
pageSize: 20,
cacheClass: Cache,
structure: structure,
noDataMessage: "No contacts found",
modules: [SingleSort]}, contactTab);
contactGrid.startup();
}
Here is how I want to populate the grid:
function contactLoad(acctIds) {
var grid = registry.byId("contactGrid");
grid.model.clearCache();
grid.setStore(JsonRest({target:"//localhost:8080/program/contacts/byAccount/" + acctIds}));
grid.body.refresh();
}
The correct Json response is being returned (as viewed on console):
{
"description": "Mike is a cool guy",
"email": "mike#mike.net",
"firstName": "Mike",
"id": 1503,
"lastName": "Smith",
"mobileNumber": "555-555-5555"
}
... but I can't get the grid to show the new data.
Any help would be appreciated!
Thank you
I tried many additional ways, without success...
This is where I am stuck - not sure what else to try.
I make the JsonRest call, get back the Json Object, and print it out to console.
Seeing that the json response looks good I try to setStore and this error is thrown: "s.query is not a function in dojo.js" (line 382). Is this a bug, or am I missing something? Thank you.
// s.query is not a function in dojo 10.0.1
grid.model.clearCache();
var store = new JsonRest({target:"//localhost:8080/program/contacts/byAccount"});
store.get(acctIds).then(function(items){
console.log(items);
grid.setStore(items);
});
grid.body.refresh();
I found it. Change:
grid.setStore(items);
to
grid.setStore(new ItemFileReadStore({data: {items : result}}));
Does anyone know how to just use JsonRest and not also include ItemFileReadStore?
Thank you,
Chris
My little piece of advice is to try to set store up once and use filter instead.
grid.filter({"acctId":"..."});
The second thing is that store sometimes requires idAttribute definition i.e.
JsonRestStore({target:"...", idAttribute:"id"});

Combine two DataTable Columns into one using Javascript

I'm currently working with Groovy/Grails and Javascript.
The code I am currently working with doesn't seem to follow a standard of how DataTables are implemented (at least not what I can see; I'm new to using DataTables and I can't find anything that is similar to what I'm seeing)
I need to combine the Survey Name and Type columns into a single column.
Example data within the "Survey Name / Type" column: "This is my Survey Name (Type)"
Controller:
The Table definitions are declared in the Controller. I'm not quite sure why they are defined here rather than on the gsp...
def impTableConfigs = [
id: [ title: '', sortIndex: 'id', visible: false ],
surveyId: [ title: 'Survey ID Number', sortIndex: 'surveyId', visible: true ],
surveyName: [ title: 'Survey Name', sortIndex: 'surveyName', visible: true],
type: [ title: 'Survey Type', sortIndex: 'type.code', visible: true]
]
def imp = {
// Check is user is logged in
// Check the users role
def dataMemberNames = getDataMemberNames(impTableConfigs)
def editingShtuff = userService.getUserEditing()
withFormat{
html{
return [
title: "Surveys",
editingShtuff : editingShtuff ,
selectedRefugeId: params.filter,
colNames: dataMemberNames,
colTitles: dataMemberNames.collect{
impTableConfigs[it]["title"]
}
]
}
json{
def args = getListDataParams(impTableConfigs, dataMemberNames, editingShtuff)
def results = getFormattedImpListData(
impTableConfigs,
editingShtuff ,
args.refuge,
args.max,
args.offset,
args.sort,
args.sortDir
)
render results as JSON
}
}
}
GSP
$(document).ready(function() {
var ops = {
editAction:'${createLink(controller:"survey", action:"edit")}',
source:'${createLink(controller:"report", action:"imp.json")}?filter='+$("#filter option:selected").val(),
swfUrl:'${resource(dir:'css/data-tables-tabletools',file:'copy_csv_xls_pdf.swf')}',
colNames:<%= colNames as JSON %>,
selectable: false,
useCache: false,
csvAction: '${createLink(action:"imp_download_csv")}',
pdfAction: '${createLink(action:"imp_download_pdf")}',
csvParams: getFilterParam,
pdfParams: getFilterParam
};
// Initialize dataTable
var table = new primr.dataTable("#dataTable", ops, {
aoColumnDefs: [ { aTargets: [8], bSortable: false }]
});
window.table = table;
// Connect filter events
$("#filter").change(function(){
var filter = $("#filter option:selected").val();
table.changeSource("${createLink(controller:"report", action:"imp.json")}?filter=" + filter);
})
});
HTML within the GSP
<table id="dataTable">
<thead>
<tr>
<g:each in="${colTitles}" var="it" status="i">
<th>${it}<sup>${i}</sup></th>
</tr>
</thead>
<tbody>
</tbody>
I'm thinking I need to move the column definitions from the Controller to the GSP and put them in the aoColumnDefs and formatting the surveyName to concatonate the 2 columns together? I'm hesistent to do this, however, as the impTableConfigs variable is used in multiple methods within the Controller. (I've included one such method).
Nevermind, I had already solved the issue but my browser was caching the domain object and controllers.
I put a getter in the Domain Object to concatonate the column values and put it in the impTableConfigs
def impTableConfigs = [
id: [ title: '', sortIndex: 'id', visible: false ],
surveyId: [ title: 'Survey ID Number', sortIndex: 'surveyId', visible: true ],
surveyNameAndType: [title: 'Survey Name/(Type)', sortIndex: 'surveyName', visible: true],
//surveyName: [ title: 'Survey Name', sortIndex: 'surveyName', visible: true ],
//type: [ title: 'Survey Type', sortIndex: 'type.code', visible: true ],
]

Categories

Resources