Could you please assist me with this issue related to Bootstrap - Jquery Table?
I would like to retrieve data from a database server In JSON Format (through an ajax call) into a bootstrap DataTable and then reload the DataTable only.
Here you are the code, this will be run once pressed the click button (search):
var prova = null;
$(document).ready(function(){
prova = $('#prova_table').DataTable({
paging: true,
searching: false
});
prendivalori();
});
function prendivalori() {
$("#bottone").click(function() {
$("#prova_table").empty();
var sopravvissuti = $('#sopravvissuti').val();
var vita = $('#vita').val();
var provincia = $('#provincia').val();
var campi = $('#campi').val();
var table = $('#prova_table');
$.ajax({
type: 'GET',
url: './php/select.php',
data: {'sopravvissuti': sopravvissuti, 'vita': vita, 'provincia':provincia, 'campi':campi},
dataType: 'json',
success: function(data) {
table.append("<thead><tr><th class='th-sm'>Cognome</th><th class='th-sm'>Nome</th><th class='th-sm'>Sesso</th></tr></thead>");
console.log(data);
len=data[0].length;
table.append("<tbody>");
for(i=0; i< len; i++){
temp=data[0][i]
table.append("<tr><td>" + temp[1] + "</td><td>" + temp[0] + "</td><td>"
+ temp[2] +"</td></tr>");
}
table.append("</tbody>");
$('#prova_table').DataTable().ajax.reload();
}
,
error: function(data) {
alert('Assicurarsi di aver selezionato tutte le caselle');
}
});
});
};
Here you are the error message received once clicked button data...
DataTables warning: table id=prova_table - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1
The json data received from the server are correct because we can see them properly into the table but we are unable to use all the functions Bootstrap DataTable provides like Pagination search and number of entries....
I'm using all the updated links for running the website ..
ETC ECT
Here you are a JSON response:
Many thanks in advance for all you kind support
Have a nice day
Andrea
You should not do table.append() and any other direct dom changes on table.
Jquery data table will do this for you if you pass options to it in right way.
Do it this way.
First initialize the datatable like below with column names if available
var table = $("#myTable").DataTable({
data:[],
columns: [
{ "data": "Cognome" },
{ "data": "Nome" },
{ "data": "Sesso" },
{ "data": "data di nascita" }
],
});
in on click of button, do a get ajax call and in done callback clear the table table.clear().draw(); and table.rows.add(result).draw() to render data to the table.
$.ajax({
url: "https://www.mocky.io/v2/5e89289e3100005600d39c17",
type: "get",
}).done(function (result) {
table.clear().draw();
table.rows.add(result).draw();
})
JSFiddle : https://jsfiddle.net/k0d1mzgL/
var table = $("#myTable").DataTable({
data:[],
columns: [
{ "data": "Cognome" ,"title": "Cognome"},
{ "data": "Nome" ,"title": "Nome"},
{ "data": "Sesso" ,"title": "Sesso"},
{ "data": "data di nascita","title": "data di nascita" }
],
});
$("#getDataBtn").click(function(){
$.ajax({
url: "https://www.mocky.io/v2/5e89289e3100005600d39c17",
type: "get",
}).done(function (result) {
table.clear().draw();
table.rows.add(result).draw();
}).fail(function (jqXHR, textStatus, errorThrown) {
//if failed
console.log("Due to https issue,this request cant be made, go check jsfiddle link provided in answer");
});
});
<link href="//cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css" rel="stylesheet" >
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<table id="myTable">
</table>
<button id="getDataBtn">Get data</button>
Related
I have a problem here, first I create data tables after I select the user using select2, so the data is dynamic according to the selected user, then next to it there is an update data button, here serves to update the data from the API if there is the latest data, for the process the data update is no problem, but there is a problem in the data tables process where after the update process, the data tables don't want to be redrawn
$("#name").on("change",function(){
var cek_id = this.value;
$("#user_id").val(cek_id);
console.log(cek_id);
$('#getData').DataTable().clear().destroy();
var i = 1;
var VendorClient = $("#getData").DataTable({
order: [ 0, "asc" ],
processing: true,
serverSide: false,
ajax: "{{route('get-user-data')}}"+"/"+cek_id,
columns: [{
data: null,
render: function ( data, type, full, meta ) {
return meta.row+1;
} },
{
data: "fullname",
name: "fullname",
orderable:false
},
{
data: "date",
name: "date",
orderable:false
}
]
});
});
and here is the process when the data update is clicked
$("#get_data").on("click",function(){
var cek_id = $("#user_id").val();
var url = "{{route('get-update-data')}}"+"/"+cek_id,
$.ajax({
type: "get",
url: url,
dataType: "json",
success:function(data){
if(data.status=='success'){
$('#getData').data.reload();
}else{
$('#getData').data.reload();
}
}
});
});
I have tried various methods, including creating a globe variable for VendorClient, then after response ajax i'm adding this code VendorClient.ajax.reload(null, false); and get errorr (index):406 Uncaught (in promise) TypeError: Cannot read property 'ajax' of undefined
but it's not working, any ideas?
Try to redraw the table:
$('#getData').DataTable().clear().draw();
or
$('#getData').DataTable().columns.adjust().draw();
or
$('#getData').DataTable().columns.adjust().draw(false);
I am developing a web application for myself to learn JavaScript/jQuery, and I am trying to use dataTables plug-in for display data on page.
I am failing to implement Child Rows, to detail my data - I get "Uncaught ReferenceError" when tying to expand child row. I found on my searches, solutions for similar problems; but I'm having trouble applying to my code due the way I structured it for get data from a PHP file.
On solution I found, this problem was generated for using different variable names for the table on dataTables settings and click event.
In my case, my dataTables settings is inside a callback function, due to PHP request (It was the way I successfully did it work, after long hours trying - I was having problems with async on JavaScript), therefore I don't have it as a variable to make the reference.
The way I am getting data from PHP it's working, but I am not sure if it is the most appropriate manner.
I am looking for a solution to set the Child Rows without messing up my PHP request. This solution can be either by changing the way data is get from PHP or the way Child Rows is setted.
function dataJSON(callback) {
$.ajax({
url: "historicoTransacoes.php",
type: "GET",
dataType: "html",
}).done(function (data) {
callback(data);
}).fail(function () {
console.log("Erro na requisição");
});
};
function dataJSON2(data) {
d = JSON.parse(data);
console.log(d)
var table = $('#ultimosLancamentos').dataTable({
//"bProcessing": true,
//"serverSide": true,
data: d,
paging: true,
ordering: false,
info: true,
columns: [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{data: "local"},
{data: "tipotransacao"},
{data: "contain"},
{data: "contaout"},
{data: "valor"},
{data: "datatransacao"}
]
});
}
$('#ultimosLancamentos tbody').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = table.row(tr);
if (row.child.isShown()) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
} else {
// Open this row
row.child(format(row.data())).show();
tr.addClass('shown');
}
});
function format(d) {
// `d` is the original data object for the row
return '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">' +
'<tr>' +
'<td>' + d.descricao + '</td>' +
'</tr>' +
'</table>';
}
$(document).ready(function () {
dataJSON(dataJSON2);
var table = $('#ultimosLancamentos').dataTable;
});
Make it work with these changes:
function dataJSON() {
var d=[];
$.ajax({
url: "historicoTransacoes.php",
type: "GET",
dataType: "html",
async: false,
success : function(data) {
//console.log(data);
d.push(data);
}, error : function(req, err) {
console.log(err);
}
});
//console.log(d[0]);
return JSON.parse(d[0]);
};
function format(d) {
// `d` is the original data object for the row
return '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">' +
'<tr>' +
'<td>' + d.descricao + '</td>' +
'</tr>' +
'</table>';
}
d=dataJSON();
//console.log(d);
$(document).ready(function () {
var table = $('#ultimosLancamentos').DataTable({
//"bProcessing": true,
//"serverSide": true,
data: d,
paging: true,
ordering: false,
info: true,
columns: [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{data: "local"},
{data: "tipotransacao"},
{data: "contain"},
{data: "contaout"},
{data: "valor"},
{data: "datatransacao"}
]
});
$('#ultimosLancamentos tbody').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = table.row(tr);
if (row.child.isShown()) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
} else {
// Open this row
row.child(format(row.data())).show();
tr.addClass('shown');
}
});
});
The key was setting ajax async propertie to 'false', so I could pass the Json from request to a JavaScript variable.
Still don't know if it is the most apporpriete way, but it worked.
Any tips for improve this code are still welcome!
I have a Django Python webapp , i have a function :
def showreport(newrequest) :
rep1 = get_report_data(newrequest,2)
data={['columns':rep1[0],'rows':rep1[1]}
return JsonResponse(data,safe=False)
i call this function from javascript in HTML page , the data return is an array with two elements, 1 represent columns and the other the data.
I want to present in the HTML page the data in a DataTable object , and since the columns and data is dynamic i want to create the DataTable dynamically
In the HTML
In JavaScript
$(document).ready(function () {
$("#showresults").on('click', function(evt) {
evt.preventDefault();
$('#show_loading').show();
$('#theTable').hide();
froms = document.getElementById('startdate').value;
tos = document.getElementById('todate').value;
$.ajax({
type: "POST",
url: 'showreport',
data: {
'start_date' : froms,
'end_date' :tos,
'csrfmiddlewaretoken': '{{ csrf_token }}'
},
success: function (data, textStatus, jqXHR) {
$('#show_loading').hide();
var rowSet=data['rows'];
var columnset =data['columns'];
$('#theTable').DataTable({
"processing": true,
searching: false,
paging: false,
"bInfo" : false,
columns: [columnset] ,
data: [rowSet]
} );
$('#theTable').show();
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$('#show_loading').hide();
alert("Error, please try again!");
}
});
});
});
Now the problem i have is that the Columns are not presented and the data is presenting only 1 row and it is not separated to columns.
In inspect mode , i can see
{"rows": [["Test1", "Test2"],["Test3", "Test4"] etc..., "columns": ["col1","col2"]}
What am i doing wrong.
Thanks,
N
I think you have an array of an array :)
try
change this
columns: [columnset],
data: [rowSet]
to this
columns: columnset,
data: rowSet
I'm a newbie in ajax, I've created this array through a function in js from a btn table: I've tried it many ways with no success, there's nothing printed in my *.php.. even with print_r, var__dump, etc
console.log(data)
{"datos":[{"value":false,"id":"173"},{"value":false,"id":"172"},{"value":false,"id":"171"},{"value":false,"id":"170"}]}
big question is: How can I pass this array to php, because I need to update a table sql with those values
JS:
$('#update').click(function(e){
e.preventDefault();
var datos = [],
data = '',
checkStatus = document.getElementsByName('check');
for(var i=0;i<checkStatus.length;i++){
var item = {
"value": checkStatus[i].checked,
"id": checkStatus[i].getAttribute('data-id')
}
datos.push(item);
}
data = JSON.stringify({datos:datos});
$.ajax({
type: "POST",
url: "updateTable.php",
datatype: "json",
data: {data},
cache: false,
success: function(){
console.log(data);
}
});
});
PHP:
????????
On the server side ..
var_dump(json_decode($json));
or for each
$json = '{"foo-bar": 12345}';
$obj = json_decode($json);
print $obj->{'foo-bar'}; // 12345
this is related to my previous question about jqgrid. im doing now a search button that would search my inputed text from the server and display those data (if there is) in the jqgrid. Now, what i did is i create a global variable that stores the filters. Here's my javascript code for my searching and displaying:
filter = ''; //this is my global variable for storing filters
$('#btnsearchCode').click(function(){
var row_data = '';
var par = {
"SessionID": $.cookie("ID"),
"dataType": "data",
"filters":[{
"name":"code",
"comparison":"starts_with",
"value":$('#searchCode').val(),
}],
"recordLimit":50,
"recordOffset":0,
"rowDataAsObjects":false,
"queryRowCount":true,
"sort_descending_fields":"main_account_group_desc"
}
filter="[{'name':'main_account_group_code','comparison':'starts_with','value':$('#searchCode').val()}]";
$('#list1').setGridParam({
url:'json.php?path=' + encodeURI('data/view') + '&json=' + encodeURI(JSON.stringify(par)),
datatype: Settings.ajaxDataType,
});
$('#list1').trigger('reloadGrid');
$.ajax({
type: 'GET',
url: 'json.php?' + $.param({path:'data/view',json:JSON.stringify(par)}),
dataType: Settings.ajaxDataType,
success: function(data) {
if ('error' in data){
showMessage('ERROR: ' + data["error"]["msg"]);
}
else{
if ( (JSON.stringify(data.result.main.row)) <= 0){
alert('code not found');
}
else{
var root=[];
$.each(data['result']['main']['rowdata'], function(rowIndex, rowDataValue) {
var row = {};
$.each(rowDataValue, function(columnIndex, rowArrayValue) {
var fldName = data['result']['main']['metadata']['fields'][columnIndex].name;
row[fldName] = rowArrayValue;
});
root[rowIndex] = row;
row_data += JSON.stringify(root[rowIndex]) + '\r\n';
});
}
alert(row_data); //this alerts all the data that starts with the inputed text...
}
}
});
}
i observed that the code always enter this (i am planning this code to use with my other tables) so i put the filter here:
$.extend(jQuery.jgrid.defaults, {
datatype: 'json',
serializeGridData: function(postData) {
var jsonParams = {
'SessionID': $.cookie("ID"),
'dataType': 'data',
'filters': filter,
'recordLimit': postData.rows,
'recordOffset': postData.rows * (postData.page - 1),
'rowDataAsObjects': false,
'queryRowCount': true,
'sort_fields': postData.sidx
};
return 'json=' + JSON.stringify(jsonParams);
},
loadError: function(xhr, msg, e) {
showMessage('HTTP error: ' + JSON.stringify(msg) + '.');
},
});
now, my question is, why is it that that it displayed an error message "Server Error: Parameter 'dataType' is not specified"? I already declared dataType in my code like above but it seems that its not reading it. Is there anybody here who can help me in this on how to show the searched data on the grid?(a function is a good help)
I modified your code based on the information from both of your questions. As the result the code will be about the following:
var myGrid = $("#list1");
myGrid.jqGrid({
datatype: 'local',
url: 'json.php',
postData: {
path: 'data/view'
},
jsonReader: {
root: function(obj) {
var root = [], fields;
if (obj.hasOwnProperty('error')) {
alert(obj.error['class'] + ' error: ' + obj.error.msg);
} else {
fields = obj.result.main.metadata.fields;
$.each(obj.result.main.rowdata, function(rowIndex, rowDataValue) {
var row = {};
$.each(rowDataValue, function(columnIndex, rowArrayValue) {
row[fields[columnIndex].name] = rowArrayValue;
});
root.push(row);
});
}
return root;
},
page: "result.main.page",
total: "result.main.pageCount",
records: "result.main.rows",
repeatitems: false,
id: "0"
},
serializeGridData: function(postData) {
var filter = JSON.stringify([
{
name:'main_account_group_code',
comparison:'starts_with',
value:$('#searchCode').val()
}
]);
var jsonParams = {
SessionID: $.cookie("ID"),
dataType: 'data',
filters: filter,
recordLimit: postData.rows,
recordOffset: postData.rows * (postData.page - 1),
rowDataAsObjects: false,
queryRowCount: true,
sort_descending_fields:'main_account_group_desc',
sort_fields: postData.sidx
};
return $.extend({},postData,{json:JSON.stringify(jsonParams)});
},
loadError: function(xhr, msg, e) {
alert('HTTP error: ' + JSON.stringify(msg) + '.');
},
colNames:['Code', 'Description','Type'],
colModel:[
{name:'code'},
{name:'desc'},
{name:'type'}
],
rowNum:10,
viewrecords: true,
rowList:[10,50,100],
pager: '#tblDataPager1',
sortname: 'desc',
sortorder: 'desc',
loadonce:false,
height: 250,
caption: "Main Account"
});
$("#btnsearchCode").click(function() {
myGrid.setGridParam({datatype:'json',page:1}).trigger("reloadGrid");
});
You can see the code live here.
The code uses datatype:'local' at the beginning (at the 4th line), so you will have no requests to the server if the "Search" button is clicked. The serializeGridData the data from the postData parameter of serializeGridData will be combined with the postData parameter of jqGrid (the parameter "&path="+encodeURIComponent('data/view') will be appended). Additionally all standard jqGrid parameters will continue to be sent, and the new json parameter with your custom information will additionally be sent.
By the way, if you want rename some standard parameters used in the URL like the usage of recordLimit instead of rows you can use prmNames parameter in the form.
prmNames: { rows: "recordLimit" }