Datatable - Insert JSON data to the table - datatables

I would like to insert JSON data into my table but I can make it to work, I keep getting error:
datatables requested unknown parameter 0 for row 0
var myTable = $('#my_logs').DataTable({
"paging": true,
"lengthChange": true,
"searching": true,
"ordering": true,
"info": true,
"autoWidth": true
});
$( "#getResults" ).click(function() {
$.ajax({
url: "http://www.myurl.com/data",
data: {
"from_date": from_date,
"to_date": to_date
},
type: "POST",
timeout: 30000,
dataType: "json", // "xml", "json"
success: function(logs) {
$.each(logs, function( index, value ) {
myTable.clear().draw();
myTable.row.add({
"Date": "1234",
"User Name": "1234",
"Class": "1234",
"Function": "1234",
"Action": "1234",
"Description": "1234"
}).draw();
});
},
error: function(jqXHR, textStatus, ex) {
alert(textStatus + "," + ex + "," + jqXHR.responseText);
}
});
});
The data I am getting from the AJAX respond it's something like that:
[
{
"log_time":"2015-12-27 09:42:21",
"user_name":"Me",
"class_name":"login",
"class_function":"authentication",
"action_title":"User login",
"action_description":"I am logged in"
},
{
"log_time":"2015-12-27 09:42:21",
"user_name":"me",
"class_name":"dashboard",
"class_function":"index",
"action_title":"Admin dashboard",
"action_description":"I am logged in"
}
]

You were nearly there. I was right about adding columns, see this working JSFiddle: https://jsfiddle.net/annoyingmouse/gx3ktawn/
Basically you need to tell the DataTable what to do with the data you give it, you also need to make sure you don't clear the data in each iteration of your response ;-).
Telling the DataTable the structure of your data also helps in taht you can add each row individually. You could also add the whole array as well (myTable.clear().rows.add(logs).draw();) rather than clear the table, iterate over the rows in your log and add each one and then draw the table.
var jsonData = [{
"log_time": "2015-12-27 09:42:21",
"user_name": "Me",
"class_name": "login",
"class_function": "authentication",
"action_title": "User login",
"action_description": "I am logged in"
}, {
"log_time": "2015-12-27 09:42:21",
"user_name": "me",
"class_name": "dashboard",
"class_function": "index",
"action_title": "Admin dashboard",
"action_description": "I am logged in"
}];
var myTable = $('#my_logs').DataTable({
"paging": true,
"lengthChange": true,
"searching": true,
"ordering": true,
"info": true,
"autoWidth": true,
"data": [],
"columns": [{
"title": "Date",
"data": "log_time"
}, {
"title": "User Name",
"data": "user_name"
}, {
"title": "Class",
"data": "class_name"
}, {
"title": "Function",
"data": "class_function"
}, {
"title": "Action",
"data": "action_title"
}, {
"title": "Description",
"data": "action_description"
}]
});
$(document).ready(function() {
$("#getResults").click(function() {
$.ajax({
url: '/echo/json/',
data: {
json: JSON.stringify(jsonData)
},
type: "POST",
timeout: 30000,
dataType: "json", // "xml", "json"
success: function(logs) {
myTable.clear();
$.each(logs, function(index, value) {
myTable.row.add(value);
});
myTable.draw();
},
error: function(jqXHR, textStatus, ex) {
alert(textStatus + "," + ex + "," + jqXHR.responseText);
}
});
});
});
Hope that helps.

Related

Indexing custom properties with Google Cloud Search API

We are having issues indexing metadata with items added to Google Cloud Search with 3rd-party datasources, using the REST API. We are following this guide: https://developers.google.com/cloud-search/docs/guides/schema-guide.
What we tried: uploaded the schema successfully ✅, indexed some items ✅, made them available in the search UI ✅, but it seems the properties and facets not showing up whether it’s in the green metadata bits in search results or in API results -- we get an empty structuredData object. Search results seem to only query the content.inlineContent and nothing else. We’re not getting any errors from the API when we make the index request (using https://developers.google.com/cloud-search/docs/reference/rest/v1/indexing.datasources.items/index_). It seems like it’s just ignoring everything in structuredData.
Other attempts: In addition to the REST API, we’ve also used the official nodejs SDK, (which has additional validation because it’s in TypeScript), to no avail. We’ve verified that auth params are correct (it returns 401 otherwise) and that there are no other validation issues (it returns 400 otherwise). Requests return 200 and do upload successfully, just not the structuredData. The original schema upload was also successful (200), and the response included the full schema we gave.
What are we missing?
schema JSON:
{
"objectDefinitions": [{
"name": "page",
"options": {
"displayOptions": {
"objectDisplayLabel": "Page",
"metalines": [
{
"properties": [
{
"propertyName": "title"
},
{
"propertyName": "content"
},
{
"propertyName": "author"
},
{
"propertyName": "siteSection"
}
]
}
]
}
},
"propertyDefinitions": [
{
"name": "title",
"isReturnable": true,
"isWildcardSearchable": true,
"isSuggestable": true,
"isRepeatable": false,
"isFacetable": false,
"textPropertyOptions": {
"operatorOptions": {
"operatorName": "title"
}
},
"displayOptions": {
"displayLabel": "Title"
}
},
{
"name": "content",
"isReturnable": true,
"isRepeatable": false,
"isFacetable": false,
"htmlPropertyOptions": {
"retrievalImportance": {
"importance": "DEFAULT"
}
},
"displayOptions": {
"displayLabel": "Content"
}
},
{
"name": "author",
"isReturnable": true,
"isRepeatable": true,
"isFacetable": true,
"textPropertyOptions": {
"operatorOptions": {
"operatorName": "author"
}
},
"displayOptions": {
"displayLabel": "Author(s)"
}
},
{
"name": "siteSection",
"isReturnable": true,
"isWildcardSearchable": false,
"isSuggestable": false,
"isRepeatable": false,
"isFacetable": true,
"textPropertyOptions": {
"operatorOptions": {
"operatorName": "sitesection"
}
},
"displayOptions": {
"displayLabel": "Site Section"
}
}
]
}]
}
indexing code:
const version = '4';
const apiUrl = `https://cloudsearch.googleapis.com/v1/indexing/datasources/${sourceId}/items/exampleItem:index`;
const title = "Example Item";
const url = "https://example.com";
fetch(apiUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + token,
},
body: JSON.stringify({
item: {
name: `datasource/${sourceId}/items/exampleItem`,
acl: {
readers: [
{
gsuitePrincipal: {
gsuiteDomain: true,
},
},
],
},
metadata: {
title: title,
sourceRepositoryUrl: url,
objectType: "page",
},
structuredData: {
object: {
properties: [
{
name: "title",
textValues: {
values: [title],
},
},
{
name: "author",
textValues: {
values: ["Unknown Author"],
},
},
{
name: "siteSection",
textValues: {
values: ["exampleSection"],
},
},
{
name: "content",
htmlValues: {
values: [exampleContentHTML],
},
},
],
},
},
content: {
inlineContent: b64(exampleContentHTML),
contentFormat: "TEXT",
},
version: b64(version),
itemType: "CONTENT_ITEM",
},
mode: "SYNCHRONOUS",
}),
})
indexing result:
{
"name": "datasources/DATASOURCE_ID/items/exampleItem",
"acl": {
"readers": [{
"gsuitePrincipal": {
"gsuiteDomain": true
}
}]
},
"metadata": {
"title": "Example Item",
"sourceRepositoryUrl": "https://example.com",
"objectType": "page"
},
"structuredData": {
"object": {}
},
"content": {
"inlineContent": "... base 64 encoded content...",
"contentFormat": "TEXT"
},
"version": "NQ==",
"status": {
"code": "ACCEPTED"
},
"queue": "default",
"itemType": "CONTENT_ITEM"
}

JS Datatables Row Group using objects not working

Would Appreciate some assistance reviewing this code and letting me know what I may be doing wrong. I am using ajax with vb.net mvc to load data using json to the view. However, the table is not sorting to show by group.
var table = $("#TblGridInfo").DataTable({
scrollX: true,
processing: true, // for show progress bar
serverSide: true, // for process server side
filter: true, // this is for disable filter (search box)
orderMulti: true, // for disable multiple column at once
pageLength: 10,
responsive: true,
ajax: {
url: "/GenerateReport/LoadMCCProductionReport",
type: "POST",
datatype: "json",
},
columns: [
{ data: "MCC", "name": "MCC", "autoWidth": true },
{ data: "Branch", "name": "Branch", "autoWidth": true },
{ data: "MerchantProfileNum", "name": "MerchantProfileNum", "autoWidth": true },
{ data: "BusinessName", "name": "BusinessName", "autoWidth": true },
{ data: "MerchantCode", "name": "MerchantCode", "autoWidth": true },
{ data: "Months", "name": "Months", "autoWidth": true },
{ data: "TotalTrans", "name": "TotalTrans", "autoWidth": true },
{ data: "Volume", "name": "Volume", "autoWidth": true }
],
order: [[0, "asc"]],
rowGroup: {
dataSrc: "MCC"
}
});

Cannot get Buttons csv working in DataTables 1.10.11

I am upgrading an existing site that was using DataTables 1.9.4 and TableTools 2.0.3 to use DataTables 1.10.11. I cannot get the csv button to show up on my page.
I replaced
"oTableTools": {
"sSwfPath": "scripts/jquery/TableTools-2.0.3/media/swf/copy_csv_xls.swf",
"sRowSelect": "multi",
"aButtons": [
{
"sExtends": "text",
"sButtonText": t.cmdMarkSelectedInvoiced,
"fnClick": function (nButton, oConfig, oFlash) {
vr.markSelectedInvoiced();
}
},
{
"sExtends": "csv",
"sButtonText": t.cmdExportSelectedToCSV,
"bSelectedOnly": true
},
{
"sExtends": "csv",
"sButtonText": t.cmdExportAllToCSV
},
{
"sExtends": "select_none",
"sButtonText": t.cmdDeselectAll
}
]
},
with
"buttons": ['csv'],
the new initialization for the datatable is:
var bla = $('#someelement').DataTable({
"buttons": [
'csv'
],
"pagingType": "simple",
"destroy": true,
"stateSave": true,
"stateSaveCallback": function (settings, data) {
vr.saveDtState(data);
},
"stateLoadCallback": function (settings) {
return vr.dtSavedState(settings);
},
"pageLength": 10,
"language": {
"emptyTable": t.tblInfoNoDesignRequestFound,
"infoEmpty": t.tblInfoNoDesignRequestFound,
"zeroRecords": t.tblInfoNoDesignRequestFound,
"info": ct.tblInfoTxtDisplayingXtoYofTotal,
"infoFiltered": ct.tblInfoTxtFilteredFromMax,
"lengthMenu": ct.tblInfoTxtShow + ' <select>' + '<option selected value=10>10</option>' + '<option value=15>15</option>' + '<option value=20>20</option>' + '<option value=25>25</option>' + '<option value=-1>' + ct.txtAll + '</option>' + '</select> ' + ct.tblInfoTxtRows,
"search": ct.tblInfoTxtFilter,
"paginate": {
"next": ct.tblInfoTxtNextPage,
"previous": ct.tblInfoTxtPreviousPage
}
},
"ordering": true,
"order": [],
"stripeClasses": [
'myodd',
'myeven'
],
"data": vr.dataObj.data,
"columns": [
{
"data": "companyLocation",
"title": ct.chCompanyLocation
},
{
"data": function (source, type, val) {
if (type === 'display' || type === 'filter') {
return u.jsonToLocalDate(source.requestStatusDateUtc, false);
}
return source.requestStatusDateUtc;
},
"title": ct.chDate
},
{
"data": function (source, type, val) {
return vr.formattedNameSizeAndOrient(source, type)
},
"title": ct.chLogoName
},
{
"data": function (source, type, val) {
return vr.formattedDrInfo(source, type)
},
"title": ct.chDRNumber
},
{
"data": "requestStatusDescription",
"title": ct.chStatus
},
{
"data": "invoiceAmount",
"title": ct.chInvoiceAmount,
"orderable": false,
"className": "rightJustify"
},
{
"data": "invoiceCurrency",
"bSortable": false
},
{
"data": "requestedBy",
"title": ct.chCreatedByName,
"orderable": false
}
],
"initComplete": function () {
vr.loadColumnSelects('viewRequestsDataTable', this, columnSelects);
}
});
You need to specify the dom: parameter.

Cannot load jsonp data into datatables

I am creating a datatables as follows:
var table = $('#details').DataTable({
"ajax": {
"url": "http://myapi/code",
"dataType": "jsonp",
"dataSrc": ""
},
"columns": [{
"data": "name"
},{
"data": "initials"
}]
});
and my data structure is:
{
"name":"john Doe",
"initials":"JD"
}
But datatables keeps on displaying "No matching records found".
What am I doing wrong?

Sencha Touch Maintain Different Stores From Same Json

I would like to be able to maintain different stores from the same json where the model for each store is the same. Each store would need to be updated based on its root property assignment. Please see below for a sample json, store, and model, in which case each store would be updated based on the json's root property value (category 1, category 2, etc.). The goal is to be able to bind a nested list in my application to different stores on the fly, rather than call setProxy to change the url setting on a single store. Also, the json needs to be in this format. Thanks for your help and please let me know if I can provide clarification or answer any questions.
Json:
{
"items": [
{
"name": "category 1",
"status": "",
"displaytext": "",
"items": [
{
"name": "",
"status": "",
"displaytext": "",
"items": [
{
"name": "",
"status": "",
"displaytext": "",
"items": [
{
"name": "",
"status": "",
"displaytext": "",
"leaf": true
}
]
}
]
}
]
},
{
"name": "category 2",
"status": "",
"displaytext": "",
"items": [
{
"name": "",
"status": "",
"displaytext": "",
"items": [
{
"name": "",
"status": "",
"displaytext": "",
"leaf": true
}
]
}
]
},
{
"name": "cateory 3",
"status": "",
"displaytext": "",
"items": []
},
{
"name": "category 4",
"status": "",
"displaytext": "",
"items": []
}
]
}
Model:
Ext.define('MyApp.model.myModel', {
extend: 'Ext.data.Model',
config: {
fields: [
{
name: 'name',
type: 'string'
},
{
name: 'status',
type: 'string'
},
{
name: 'displaytext',
type: 'string'
}
]
}
});
Store 1, 2, 3, etc:
Ext.define('MyApp.store.storeCategory1', {
extend: 'Ext.data.TreeStore',
requires: [
'MyApp.model.myModel'
],
config: {
model: 'MyApp.model.myModel',
storeId: 'myStore',
autoLoad: false,
proxy: {
type: 'ajax',
url: '/path/to/file.json',
reader: {
type: 'json',
rootProperty: 'items'
}
}
}
});
I think you best bet would be to make a server request independent of the Store's proxy. On success, split up the data into the different stores as needed. It's fine to preprocess data this way, especially if you need to split one large data response into multiple data stores. For example:
Ext.Ajax.request({
url: 'path/to/file.json',
success: function(response){
// process server response here
var json = Ext.decode(response.responseText);
for(var i=0, l=json.items.length, i<l; i++){
// start distributing the data to your different stores here
}
}
});
Hope this helps.