Data tables add update delete and edit - javascript

My question is about how can I edit, delete and add data in Datatables
jsfiddle CODE
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Test</th>
<th>Description</th>
<th>Result</th>
<th>Start Time</th>
<th>End Time</th>
</tr>
</thead>
$(document).ready(function (){
var table = $('#example').DataTable({
"ajax": "https://api.myjson.com/bins/575cy",
"columns": [
{ "data": "tId" },
{ "data": "description"},
{ "data": "rst" },
{ "data": "startDate" },
{ "data": "endDate"}
]
});
});
1: In above link there is code by someone I want to know if it's possible to add, update and delete data.
2: I also want to know how update, delete and edit will change data on json page as well so after refresh or on reopening the page I see updated not the previous data.
EIDTED:: I also have a MySQL database using with servlet and JSP , java if anyone can help me find a solution on using datatables with that as well and edit and delete as well...
Hope I have cleared myself properly.

Related

Trying to display a table with data from API, array inside JSON Object ANGULAR

I'm working in a project to help a friend, so most of the code in the services and the backend was already there, so I've been struggling with the structure and sometimes I get lost.
Here's my problem
This is the structure of the data on the API:
{
"title": "",
"iconURL": ",
"linkedRightsIDs": [
""
],
"linkedRights": [
{
"id": ,
"creationDate": "",
"sections": [
"women"
],
"defLanguage": "en",
"countryApplied": "united states",
"statesApplied": [
"all"
],
"title": "",
"translations": [
"en"
],
"disable": false,
"content": null
}
]
}
What I'm trying to achieve, is to make a table inside my component using the LinkedRights data. Right now, this structure only have 1 linkedRight (I deleted the data inside for privacy)
Anyways, here's the method regarding the service and model in my component.ts:
onModelLoadedAsync() {
super.onModelLoadedAsync();
if (this.mode == 'create') {
this.model = LocalityInfo;
} else {
if (this.model.iconURL){
this.imageSrc = this.model.iconURL;
}
}
if(this.mode == 'edit'){
const data= Object.entries(this.model.linkedRights); //this is me just testing
console.log(data);
}
}
here's the html of the table I'm trying to display, this is and edit route so there's a query param for the id in this view
<div class="table-responsive">
<table class="table table-hover">
<thead class="thead-dark">
<tr>
<th>Title</th>
<th>Sections</th>
<th>States</th>
<th>Enabled</th>
<th>Creation Date</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of data">
<td>{{item.title}}</td>
<td>{{item.sections}}</td>
<td>{{item.statesApplied}}</td>
<td>{{!item.disabled}}</td>
<td>{{item.creationDate}}</td>
</tr>
</tbody>
</table>
</div>
</div>
What I was trying to do, was to convert the JSON into an array so I could display it since there's an error that shows on the console that said this:
core.js:6456 ERROR Error: Cannot find a differ supporting object '[object Object]' of type'object'. NgFor only supports binding to Iterables such as Arrays.

load datatable from custom response

I am working on datatables. I have posted 2 questions already related to my this question this and this.
AJAX CALL:
API.call("getBasicCallAnalysisData.json", 'POST', function(data) {
basicData = data;
createTable(basicData);
}, function(error) {
console.log(error);
}, jsonStr);
this my json response from server:
{"msg":null,"code":null,"status":null,"result":[{"aNumber":"3224193861","bNumber":"3217284244","cellID":"410-01-604-30226","dateTime":"2017-06-24 23:08:09.0","duration":801,"imei":"27512671195807","imsi":"35788979525680","operatorId":1,"mscId":"2","fileId":"1"},{"aNumber":"3224193861","bNumber":"3217280585","cellID":"410-01-738-13433","dateTime":"2017-06-24 06:53:13.0","duration":198,"imei":"46341570864238","imsi":"33270572168878","operatorId":2,"mscId":"4","fileId":"2"}],"draw":1,"limit":1000,"recordsFiltered":13442,"recordsTotal":13442}
HTML TABLE :
<table id="table" class="display responsive nowrap" cellspacing="0" width="100%">
<thead style="background-color:#303641;">
<tr>
<th>ANUMBER</th>
<th>BNUMBER</th>
<th>DATETIME</th>
<th>DURATION</th>
<th>IMEI</th>
<th>IMSI</th>
<th>CELLID</th>
<th>OPRID</th>
<th>MSC ID</th>
<th>FILE ID</th>
</tr>
</thead>
</table>
and this is my function to load datatable BUT I am facing two errors:
function createTable(data) {
console.log(data);
$('#table').DataTable({
"processing": true,
"serverSide": true,
"bFilter": false,
"iDisplayLength": configData,
dom: 'Bfrtip',
buttons: ['colvis', 'print', 'csv', 'excel', 'pdf'],
searching: false,
language: {
buttons: {
colvis: 'Show/Hide Columns'
}
},
"aaData": data
});
}
The parameter data is response from server. Errors are :
DataTables warning: table id=table - Requested unknown parameter
'aNumber' for row 0, column 0. For more information about this error,
please see http://datatables.net/tn/4
and
Invalid JSON Response.
any idea, how Can i populate datatable with JSON response ?
There is two possibility to get your json into DataTables...
Use a jQuery Ajax request
Use the DataTables remote preocessing
You use the first one.
There is two main problems to your code:
A superflous DataTables attribute.
A valid JSON, but not structured as DataTables expects it.
#1
The attribute "serverSide": true, basically says that you intend to use the "remote processing". So DataTables expects now an "ajax" attribute holding the PHP address to get the JSON. This missing attribute triggered the "invalid JSON" error.
I hear you shouting loud about unclear error messages now!!! (lol)
#2
DataTables expects the data structured as an array for the whole table...
This array has to hold arrays of "row" values. Example here.
That is not what you actually have.
So I made a function to "re-arrange" the data to satisfy DataTables expectations.
console.clear();
// A function to run trhough your json and restructure the data as an array of array.
function arrangeData(data){
var datatableData = [];
for(i=0;i<data.length;i++){
var row = [
data[i].aNumber,
data[i].bNumber,
data[i].cellID,
data[i].dateTime,
data[i].duration,
data[i].imei,
data[i].imsi,
data[i].operatorId,
data[i].mscId,
data[i].fileId
];
datatableData.push(row);
}
console.log(datatableData);
return datatableData;
}
// Your original function not really changed...
function createTable(data) {
$('#table').DataTable({
"processing": true,
//"serverSide": true, // This works with the "remote preocessing" ajax attribute.
"bFilter": false,
//"iDisplayLength": configData, // I commented this one only because I did not have the "configData" variable.
dom: 'Bfrtip',
buttons: ['colvis', 'print', 'csv', 'excel', 'pdf'],
searching: false,
language: {
buttons: {
colvis: 'Show/Hide Columns'
}
},
"aaData": arrangeData(data) // I'm calling the "arrange" function here.
});
}
// This is to simulate the response you get form jQuery Ajax.
var dataset = {
msg:null,
code:null,
status:null,
result:[
{
"aNumber":"3224193861",
"bNumber":"3217284244",
"cellID":"410-01-604-30226",
"dateTime":"2017-06-24 23:08:09.0",
"duration":801,
"imei":"27512671195807",
"imsi":"35788979525680",
"operatorId":1,
"mscId":"2",
"fileId":"1"
},
{
"aNumber":"3224193861",
"bNumber":"3217280585",
"cellID":"410-01-738-13433",
"dateTime":"2017-06-24 06:53:13.0",
"duration":198,
"imei":"46341570864238",
"imsi":"33270572168878",
"operatorId":2,
"mscId":"4",
"fileId":"2"
}
],
"draw":1,
"limit":1000,
"recordsFiltered":13442,
"recordsTotal":13442
};
// Call the table draw function... Certainly in your ajax success callback.
createTable(dataset.result);
CodePen

JSON data rendering in javascript function [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 5 years ago.
I am using bootstrap table to build table with json data dynamically, when i plugged function to consume json from web service the table displays empty rows. I compared the data set and i don't see any errors either. Did anyone face this ? what am i missing ?
Script #1
var data;
$.getJSON("http://xxxxxxxx:8073/data-list", function(json){
data = json;
console.log(" data : "+JSON.stringify(data));
});
/*function to load data to first nav tab map*/
$(function () {
$('#table').bootstrapTable({
data: data
});
});
Log
console.log outputs the data as mentioned below, if i compare between hardcoded json vs json from web service it looks identical.
data : [{"index":1,"name":"MATT","company":"APPLE","key":"123333","description":"Node check"},{"index":2,"name":"Steve","company":"Zynga","key":"124333","description":"Game check"}]
Script #2
The same feature works fine if i have variable holding hardcoded json data.
var data =
[
{
"index": 1,
"name": "MATT",
"company": "APPLE",
"key": "123333",
"description": "Node check"
},
{
"index": 2,
"name": "Steve",
"company": "Zynga",
"key": "124333",
"description": "Game check"
}
]
$(function () {
$('#table').bootstrapTable({
data: data
});
});
View
<tr>
<th class="col-md-5 col-xs-5" data-field="name" data-sortable="true">Name</th>
<th class="col-md-4 col-xs-4" data-field="company" data-sortable="true">Work (Authority)</th>
<th class="col-md-3 col-xs-3" data-field="key" data-sortable="true">Magic Key</th>
</tr>
$.getJSON is asynchronous, your second function is probably going to run prior to getJSON completing and setting data. The solution is to initialize your table in the getJSON callback:
var data;
/*function to load data to first nav tab map*/
$(function () {
$.getJSON("http://xxxxxxxx:8073/data-list", function(json){
data = json;
console.log(" data : "+JSON.stringify(data));
$('#table').bootstrapTable({
data: data
});
});
});
in script #1, $.getJson is an asynchronous function.
So, following, you need to stick your table initialisation inside the async callback.
var data;
$.getJSON("http://xxxxxxxx:8073/data-list", function(json){
data = json;
console.log(" data : "+JSON.stringify(data));
$('#table').bootstrapTable({
data: data
});
});
/*function to load data to first nav tab map*/
$(function () {
$.getJSON("http://xxxxxxxx:8073/data-list", function(json){
data = json;
console.log(" data : "+JSON.stringify(data));
}).then(function(data) {
$('#table').bootstrapTable({
data: data
});
})
});
Because the data variable is not populated until the getJSON finishes. The function call is seeing data data as undefined.
http://api.jquery.com/jquery.ajax/
Because $.getJSON is asynchronous you can use the bootstrapTable load method inside your getJSON:
$('#table').bootstrapTable('load', data);
var data =[
{
"index": 1,
"name": "MATT",
"company": "APPLE",
"key": "123333",
"description": "Node check"
},
{
"index": 2,
"name": "Steve",
"company": "Zynga",
"key": "124333",
"description": "Game check"
}
];
$('#table').bootstrapTable({
});
//$.getJSON("http://xxxxxxxx:8073/data-list", function(json){
//data = json;
//console.log(" data : "+JSON.stringify(data));
$('#table').bootstrapTable('load', data);
//});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.11.1/bootstrap-table.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.11.1/bootstrap-table.min.js"></script>
<table id="table">
<thead>
<tr>
<th class="col-md-5 col-xs-5" data-field="name" data-sortable="true">Name</th>
<th class="col-md-4 col-xs-4" data-field="company" data-sortable="true">Work (Authority)</th>
<th class="col-md-3 col-xs-3" data-field="key" data-sortable="true">Magic Key</th>
</tr>
</thead>
<tbody></tbody>
</table>

Populating Datatables with php sending json

I'm having troubles identify the problem in my code.
I'm doing a searching script, and I'd like to show the results in Datatable. I have a searching form that sends data to my php file and returns a json_encode of my query results, then on ajax success, I build my table passing the results in "data": response.
The query worked just fine when I was doing it without Datatables, but since I need pagination and stuff, I need it to work on Datatables.
HTML for Table:
<div id="results">
<table id="example" class="display compact hover stripe" cellspacing="0" width="100%">
<thead>
<th>Cognome</th>
<th>Nome</th>
<th>Telefono</th>
<th>Provincia</th>
<th>Tipo Cliente</th>
<th>Amministrazione</th>
<th>Stato</th>
<th>Fonte</th>
<th>Data Ricezione</th>
<th></th>
</thead>
</table>
</div>
Javascript for Datatable:
$('#submit_src').on("click", function() {
$.ajax({
data: $("#ricerca").serialize(),
type: $("#ricerca").attr('method'),
url: $("#ricerca").attr('action'),
success: function(response) {
$('#example').dataTable( {
"data": response,
"sPaginationType": "listbox",
"bFilter": false,
"jQueryUI": true,
"processing": true,
'iDisplayLength': 25,
} );
}
});
return false;
});
"submit_src" is my button for submit ofcourse, and "ricerca" is the name of my form.
The json code I get is:
{"sEcho":0,"iTotalRecords":"35036","iTotalDisplayRecords":"1","aaData":[["stuff","stuff","stuff","stuff","stuff","stuff","stuff","stuff","stuff","stuff"]]}
Error:
DataTables warning: table id=example - Requested unknown parameter '1' for row 0.
This link may help with what you are trying to accomplish: http://datatables.net/release-datatables/examples/ajax/objects.html. It explains that DataTables expects arrays for the data; however, in order to use the objects it can be done by using the columns.data option.
I have also used DataTables without <tbody> so that should not be an issue.
Edit:
Try the following, I was able to get the 'stuff' to show in the table:
$('#example').dataTable( {
"data": response.aaData
} );
Edit 2:
jQuery(document).ready(function() {
var response = {
"sEcho":0,"iTotalRecords":"35036","iTotalDisplayRecords":"1",
"aaData": [
["stuff","stuff","stuff","stuff","stuff","stuff","stuff","stuff","stuff","stuff"]]
};
$('#example').dataTable( {
"data": response.aaData,
//"sPaginationType": "listbox",
"bFilter": false,
"jQueryUI": true,
"processing": true,
'iDisplayLength': 25
} );
});
You are probably missing the option
dataType : "json",
on you code. That might confuse the type of data recieved from the ajax script if not specified.
I believe <tbody></tbody> is required with DataTables so it knows where to put the data returned. Try adding that to your table#example.
<table id="example" class="display compact hover stripe" cellspacing="0" width="100%">
<thead>
<th>Cognome</th>
<th>Nome</th>
<th>Telefono</th>
<th>Provincia</th>
<th>Tipo Cliente</th>
<th>Amministrazione</th>
<th>Stato</th>
<th>Fonte</th>
<th>Data Ricezione</th>
<th></th>
</thead>
<tbody></tbody>
</table>

jsViews - display custom properties in object list

I have some data that I want to output using jsViews. The case is that objects in data array can have different set of attributes/columns based on some conditions. I store those attributes names in settings and would like to be able to print contents of data with all additional columns stored in a settings array. For example:
data = {
view_settings: [{
property_name: "prop1"
},
{
property_name: "prop2"
}
],
object_list: [{
id: "180",
name: "test1",
prop1: "test-prop-1",
prop2: "test-prop-2"
}
]
}
What I would like to achieve is to display contents of object_list using property listing from view_settings. Is this even possible using jsViews?
The best way to find an answer for you question is to ask it first, understand it (rubber duck method) and then find an answer.
In order to do this we need to alias objects twice. Here is my simplified jsViews template code which will display correctly data from example from my question:
<script id="template1" type="text/x-jsrender">
<table>
<thead>
<tr>
<th>Name</th>
{{for view_settings}}
<th>{{>property_name}}</th>
{{/for}}
<th></th>
</tr>
</thead>
<tbody>
{{for object_list ~view_settings=#data.view_settings}}
<tr>
<th>{{>name}}</th>
{{for ~view_settings ~object=#data}}
<th>{{:~object[property_name]}}</th>
{{/for}}
<th></th>
</tr>
{{/for}}
</tbody>
</table>
</script>
Hope this spares someones time ;)

Categories

Resources