I have an array like this:
"products": {
"111111": {
"date": "01.01.2018",
"amount": 10,
"user_id": "user1",
}
"222222": {
"date": "10.10.2018",
"amount": 15,
"user_id": "user1,
}
}
"111111" and "222222" are IDs and they are generated dynamically, depending on selected user.
I want to display the following columns: product_id, date, amount, user_id
Is there a way to populate the table when a column name is dynamic ?
Thanks!
If you can change the format of your json slightly, you can easily just assign it as an array for the data attribute when initializing datatables. If that is not an option, you could just parse it into the below format by iterating through the key-value pairs and adding that data to an array of jsons.
$(document).ready(function() {
var products = [{
"product_id": "111111",
"date": "01.01.2018",
"amount": 10,
"user_id": "user1",
},
{
"product_id": "222222",
"date": "10.10.2018",
"amount": 15,
"user_id": "user1",
}
];
var table = $('#example').DataTable({
data: products,
columnDefs: [
{ targets: 0, data: "product_id"},
{ targets: 1, data: "date" },
{ targets: 2, data: "amount" },
{ targets: 3, data: "user_id" }
]
});
});
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<link href="https://nightly.datatables.net/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
<script src="https://nightly.datatables.net/js/jquery.dataTables.js"></script>
<div class="container">
<table id="example" class="display nowrap" width="100%">
<thead>
<tr>
<th>product_id</th>
<th>date</th>
<th>amount</th>
<th>user_id</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
Related
One of my Datatable throws an error like on the title, but my other datatable running smoothly, I don't understand why I keep getting the error, I triple check every close tags, brackets etc. I also tried to minimize my data array for a second to check whats the problem and still I dont get the problem. here's my code,
Javascript:
$("#MyNameOfDatatable").DataTable({
"language": {
"emptyTable": "No data available"
},
"dom": "<'top'f>rtp<'bottom'l>",
"searching": false,
"data": res.data, //The data came from my ajax server side
"destroy": true,
"processing": true,
"serverside": true,
"info": true,
"autoWidth": false,
"lengthMenu": [[10, 20, 50, -1], [10, 20, 50, "All"]],
"columns": [
{
data: null, "orderable": true,
"render": function (data, type, full, meta) {
return meta.row + 1;
}
},
{ data: "name", orderable: false }
]
})
Html:
<table class="table table-hover table-bordered table-striped cell-border" id="MyNameOfDatatable">
<thead>
<tr class="bg-primary text-light">
<th>SEQ</th>
<th>Name</th>
</tr>
</thead>
</table>
Sample data that server throws to me:
{
"data": [
{
"name": "Lorem Ipsum",
}
]
}
Here, I am using "datatables" for my asp.net 6 web app. everything is working except "Horizontal-Scrolling" & "Only Date Property" I know that I am doing some wrong here, so please help me to solve this issue. and Thanks in advance.
My related table js file, view, index and model are given below:
"btbPending.js" is given below:
Here, I use "scrollX" for the horizontal scroll bar. But it didn't show the scroll option rather than the data table taking its extra space and looks so ugly. So where I use the "scrollX" function ?
And also I use "render: $.fn.dataTable.render.moment('x','DD/MM/YYYY')" for showing the date only property but it shows "invalid Date" in my data table. Now, also I need to know how to show this "Date-Only" property in my Data table.
var dataTable;
$(document).ready(function () {
$('#tblData').DataTable({
"scrollX": true,
});
loadDataTable();
});
function loadDataTable() {
dataTable = $('#tblData').DataTable({
"ajax": {
"url": "/Admin/BTBPending/GetAll"
},
"columns": [
{ "data": "supplierSelectList.supplier", "width": "15%" },
{ "data": "countrySelectList.country", "width": "15%" },
{ "data": "itemSelectList.item", "width": "15%" },
{ "data": "value", render: $.fn.dataTable.render.number(',', '.', 2, '$') , "width": "15%" },
{ "data": "piNo", "width": "15%" },
{ "data": "shipDate", render: $.fn.dataTable.render.moment('x','DD/MM/YYYY'), "width": "15%" },
{ "data": "buyerSelectList.buyer", "width": "10%" },
{ "data": "supplierSelectList.supplier", "width": "15%" },
{ "data": "countrySelectList.country", "width": "15%" },
{ "data": "itemSelectList.item", "width": "15%" },
{ "data": "value", render: $.fn.dataTable.render.number(',', '.', 2, '$'), "width": "15%" },
{ "data": "piNo", "width": "15%" },
{ "data": "shipDate", render: $.fn.dataTable.render.moment('x', 'DD/MM/YYYY'), "width": "15%" },
{ "data": "buyerSelectList.buyer", "width": "10%" },
]
});
}
"BTBPending" Index :
<div class="card-body">
<div class="tab-content">
<div class="tab-pane fade show active" role="tabpanel">
<div class="mb-1">
<table id="tblData" class="table table-bordered table-hover table-sm align-middle m-0" style="width:100%">
<thead class="" style="text-align:center;background-color: #17A2B8">
<tr>
<th>Supplier</th>
<th>Country</th>
<th>Item</th>
<th>Value</th>
<th>PI</th>
<th>Ship Date</th>
<th>Buyer</th>
<th>Supplier</th>
<th>Country</th>
<th>Item</th>
<th>Value</th>
<th>PI</th>
<th>Ship Date</th>
<th>Buyer</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
</div>
I cannot get values in my template while i have the data, here is my code:
code
<template>
<div>
{{project}}
</div>
</template>
<script>
export default {
props: ['id'],
data() {
return{
project:[]
}
},
created(){
this.fetchProject();
},
methods:{
fetchProject(){
var self = this;
axios.post('/showprojectvue/' +self.id).then(res => {
self.project.push(res.data);
});
},
}
}
</script>
output
[ { "id": 33, "user_id": 2, "title": "kjfsdjowhd", "slug": "kjfsdjowhd", "body": "<p>khweihgtfihrwhtg</p>", "attachment": null, "projectclass": "sthrh", "budget": 36346, "deadline": "2018-08-24", "published": "n", "runing": "n", "payment_verified": "n", "created_at": "2018-08-05 03:43:16", "updated_at": "2018-08-05 03:43:16" } ]
i cannot use any of {{project.title}} or {{project['title']}}
How can I get out my data?
As your data is an array you need to use v-for to iterate over it.
<template>
<div v-for="obj in project">
{{obj.title}}
</div>
</template>
Example,
function callMe(){
var vm = new Vue({
el : '#root',
data : {
project : []
},
methods: {
ajaxCall(){
this.project=[{ "id": 33, "user_id": 2, "title": "kjfsdjowhd", "slug": "kjfsdjowhd", "body": "<p>khweihgtfihrwhtg</p>", "attachment": null, "projectclass": "sthrh", "budget": 36346, "deadline": "2018-08-24", "published": "n", "runing": "n", "payment_verified": "n", "created_at": "2018-08-05 03:43:16", "updated_at": "2018-08-05 03:43:16" }];
}
},
})
}
callMe()
<script src="https://cdn.jsdelivr.net/npm/vue#2.5.11/dist/vue.js"></script>
<div id='root'>
<button type="button" #click="ajaxCall">Click ME</button>
<div v-for="obj in project">
Title: {{obj.title}}
<p>
Object:{{obj}}
</p>
</div>
</div>
Given the following code
// Assuming records is an array of objects
// Record is of the form {"fname": "John", "lname": "Smith", "dob": 1499994497871}
// Field mapper is
[
{
"name": "fname",
"label": "First Name",
"render": function(val){ return val}
},
{
"name": "lname",
"label": "Last Name",
"render": function(val){ return val}
},
{
"name": "dob",
"label": "Date of Birth",
"render": function(val){ return new Date(val).toDateString()}
}
]
// Assume findField returns the mapper instance for a given record in the records array
<div v-for="record in records">
<div>
<table class="table">
<tbody>
<tr v-for="(value, key) in record">
<th v-if="findField(key)">{{ findField(key).label }}</th>
<td v-if="findField(key)">{{ findField(key).render(value) }}</td>
</tr>
</tbody>
</table>
</div>
</div>
I'm making four calls to findField().
What's the Vue recommendation to storing variables inside looping structure?
In other words, after the first tr, something like:
let localInstance = findField(key)
One way is to use a component.
Vue.component("row", {
props:["map", "value"],
template:`
<tr>
<th v-if="map">{{ map.label }}</th>
<td v-if="map">{{ map.render(value) }}</td>
</tr>
`
})
And modify your template to use it.
<tr is="row" v-for="(value, key) in record"
:map="findField(key)"
:value="value">
</tr>
console.clear()
const fieldMap = [{
"name": "fname",
"label": "First Name",
"render": function(val) {
return val
}
},
{
"name": "lname",
"label": "Last Name",
"render": function(val) {
return val
}
},
{
"name": "dob",
"label": "Date of Birth",
"render": function(val) {
return new Date(val).toDateString()
}
}
]
const records = [{
"fname": "John",
"lname": "Smith",
"dob": 1499994497871
},
{
"fname": "John",
"lname": "Smith",
"dob": 1499994497871
},
{
"fname": "John",
"lname": "Smith",
"dob": 1499994497871
}
]
Vue.component("row", {
props: ["map", "value"],
template: `
<tr>
<th v-if="map">{{ map.label }}</th>
<td v-if="map">{{ map.render(value) }}</td>
</tr>
`
})
new Vue({
el: "#app",
data: {
records
},
methods: {
findField(key) {
return fieldMap.find(m => m.name === key)
}
},
})
<script src="https://unpkg.com/vue#2.2.6/dist/vue.js"></script>
<div id="app">
<div v-for="record in records">
<div>
<table class="table">
<tbody>
<tr is="row" v-for="(value, key) in record" :map="findField(key)" :value="value">
</tr>
</tbody>
</table>
</div>
</div>
</div>
I am doing a ajax request to the server to get the data.When the array is empty, I want it to be displayed in a table row "emptyTable". I get message "emptyTable", if not used aoColumnDefs, but I'm getting warning "Requested unknown parameter ... " . I do not want to receive a warning!
var searchTable = $('#baseTasks').dataTable({
bFilter: false, bInfo: false, "bLengthChange": false,
scrollY:"600px",scrollCollapse: true, paging:false,
"aaData": tasks,
"aoColumns": [
{ "mData": "name"
},{"mData": "schoolClass"
},{"mData": "complexity"
},{"mData": "author"
}]
});
if I use aoColumnDefs, I do not get warning, but I get an empty table without message "emptyTable".
"aoColumnDefs": [
{
"mData": null,
"sDefaultContent": null,
"aTargets": [ -1 ]
}],
How do I get a table with a message "emptyTable", if the aaData is an empty array?
Your code is correct. Run the code below for demonstration.
var tasks = [
{
"name": "Tiger Nixon",
"schoolClass": "System Architect",
"complexity": "$320,800",
"author": "2011\/04\/25"
},
{
"name": "Garrett Winters",
"schoolClass": "Accountant",
"complexity": "$170,750",
"author": "2011\/07\/25"
}
];
var tasksEmpty = [];
$(document).ready( function () {
var table = $('#example').DataTable({
"data": tasksEmpty,
"columns": [
{ "data": "name"},
{ "data": "schoolClass" },
{ "data": "complexity"},
{ "data": "author" }
],
"searching": false,
"info": false,
"lengthChange": false,
"scrollY":"600px",
"scrollCollapse": true,
"paging":false,
});
});
<script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<link href="//cdn.datatables.net/1.10.7/css/jquery.dataTables.css" rel="stylesheet" />
<script src="//cdn.datatables.net/1.10.7/js/jquery.dataTables.js"></script>
<table id="example" class="display" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
</tr>
</thead>
</table>
Most likely cause of Requested unknown parameter error is that your data is not structured properly or some of the properties (name, schoolClass, complexity or author) are not found.
Your data should have the following structure. Make sure that every array item has all the properties required.
var tasks = [
{
"name": "Tiger Nixon",
"schoolClass": "System Architect",
"complexity": "$320,800",
"author": "2011\/04\/25"
},
{
"name": "Garrett Winters",
"schoolClass": "Accountant",
"complexity": "$170,750",
"author": "2011\/07\/25"
}
];
Also please note that your code uses parameters for different versions of DataTables. Although newer DataTables library is backward-compatible, I have updated your code to use initialization parameters for the most recent version. Please see this migration guide for more information.
Add the below line of code to your datatable with your message set to sEmptyTable.
oLanguage: {
"sEmptyTable": "No data found.",
}