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);
Related
I am trying to show my JSON data in the table by using Data table. However, data table keep stuck in the processing like this and I don't know why.
https://jsfiddle.net/Lvmertbp/
JSON format
console.log(data)
Java controller code
#GetMapping(value="/projects")
public #ResponseBody List<Project> getProjects() {
return projectService.findAllProjects2();
}
I know this is the old question, but I have tried everything I can but it just don't work.
Try removing the success function, that seemed to work for me:
success:function(data){
console.log(data);
},
You should also check that your array is in the "data" object, if it's just a flat array you should pass an empty string to dataSrc. Working example: http://jsfiddle.net/5snrvL4m
Your server response is returning an array of result , not an object with data key array ,
So you data table will search in the result for a data array key , but not found , in your case you should specify the param dataSrc as empty , so it'll take it as ana array ,
Check here the doc
$(document).ready(function () {
$('#tableProject').DataTable({
processing: true,
serverSide: true,
ajax: {
url: "/projects",
type: "GET",
contentType: "application/json",
dataSrc: '', // <------------------------ here set empty string
data: function () {
},
success:function(data){
console.log(data);
},
},
paging:true,
columns: [
{data: "projectNumber"},
{data: "name"},
{data: "status"},
{data: "customerName"},
{data: "startDate"},
]
});
});
I'm still learning how to code js and datatables and I'm working on a crud using ajax. I have this code here:
load_data();
function load_data(is_suppliers)
{
var dataTable = $('#product_data').DataTable({
"processing":true,
"serverSide":true,
"order":[],
"ajax":{
url:"fetch.php",
type:"POST",
data:{is_suppliers:is_suppliers}
},
"columnDefs":[
{
"targets":[0,5,7,8],
"orderable":false,
},
],
});
}
This function is for column filtering and works with this code here:
$(document).on('change', '#supplier_filter', function(){
var supplier = $(this).val();
$('#product_data').DataTable().destroy();
if(supplier != '')
{
load_data(supplier);
}
else
{
load_data();
}
});
The problem is that the function initializes datatables:
var dataTable = $('#product_data').DataTable({});
and i have already initialized datatables for my crud operations so i cant use this code. How can use this function so it can work with my crud operation?
If you define the table's ajax datasource via a function, then you can determine the parameters to send along with your AJAX request at the time the call is made. Then, you can reload the datasource whenever you want, and the most current value of the filter will be send along in the payload.
Replace
"ajax":{
url:"fetch.php",
type:"POST",
data:{is_suppliers:is_suppliers}
},
With something like
ajax: function(data, callback, _settings) {
$.ajax({
type: 'POST',
url: 'fetch.php',
data: { is_suppliers: $('#supplier_filter').val() }
}).then(function(res) {
callback({ data: res });
});
},
Now, when the table first loads, it'll fetch the filter value from the filter control, and then send it along as part of the AJAX request.
Later, you can load the data again with
$('#product_data').DataTable().ajax.reload();
And at that time, it will look again at the filter widget, get the value, and send the new value along with a new AJAX request.
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 have a grid with a store which is loaded when app is launched. I have a form also to which the grid is bound to. Initially, the grid shows all records. The search form allows user to filter records. The initial load and search URLs are different. When search is clicked, I dynamically change the URL configured on the store proxy to the filter URL, pass in the form values as extraParams, and load the store. I see the request is made and a response is returned. However, my grid records dont refresh.
//grid store inside initComponent
this.store = Ext.create("Ext.data.Store",{
fields:["rptid", "text", "value", "date_created", "created_by", "active],
autoLoad:true,
proxy:{
type:"ajax",
url:"./getRpts.html",
reader:{
type:"json",
root:"data"
}
}
});
//handler for search form button
this.getRPTGrid().getStore().getProxy().url = "./getFilteredReports.html";
this.getRPTGrid().getStore().getProxy().extraParams =
this.getSearchForm().getValues();
this.getRPTGrid().getStore().load();
thats it. I confirm the request is being made to load the store and confirm the response being received in debugger. The JSON response also contains the "data" root so thats not the issue and the fields dont change either. I have done this 10,000 times before but have never experienced this. Anyone have any ideas?
I even compared the Request and Response Headers from both requests and their exactly the same minus the url and params..
Try using reload to ensure your store data.
This code below check my data after add or update, so if i add record it's automatically reload my store and select the new record.
var store = this.getRPTGrid().getStore();
Ext.Ajax.request({
method: 'POST',
url: "./getFilteredReports.html",
params: {
data: this.getSearchForm().getValues()
},
success: function(response) {
store.reload({
callback: function() {
var newRecordIndex = store.findBy(
function(record, id) {
if (record.get(
'rptid'
) === values.rptid) {
return true;
}
return false;
});
getRPTGrid.getSelectionModel().select(
newRecordIndex);
}
});
}
});
and if you want to change proxy url to update your store try to update the proxy in your model instead in your store, like this below :
Ext.define('APP.model.m_gis', {
extend: 'Ext.data.Model',
alias: 'widget.gisModel',
proxy: {
type: 'jsonp',
url: './getRpts.html',
reader: {
type: 'json',
root: 'data',
totalProperty: 'totalCount'
}
},
fields: ["rptid", "text", "value", "date_created", "created_by",
"active"
]
});
This is the store look like :
Ext.define('APP.store.s_gis', {
extend: 'Ext.data.Store',
alias: 'widget.gisStore',
model: 'APP.model.m_gis'
});
and change your proxy like you want :
var place_store = Ext.create('APP.store.s_gis');
place_store.getProxy().setExtraParam('url', "./getFilteredReports.html");
I'm trying to create a web-page in EXTJs that has two major components:
A Form (Ext.form.Panel)
A Panel (Ext.tree.Panel)
The form is supposed to get some values, which should populate tree in second panel. In the button handler of the first panel I have access to the updated JSON object, but I cannot figure out a way to refresh the TreeStore that will update the display in tree.Panel.
This is what I have so far :
Ext.define('TreeServiceData',{
config:{
data : ''
},print : function() {
console.log("Printing data: ")
console.log(this.data.children[0])
}
});
var dataObject = Ext.create('TreeServiceData');
dataObject.setData({'expanded':false,'children':[{'text':'Master','expanded':true,'leaf':false,'children':[{'text':'Child 1','expanded':true,'leaf':false,'children':[{'text':'Child 2','expanded':true,'leaf':false,'children':[{'text':'Child 3','expanded':false,'leaf':false}]}]}]}]})
Ext.define('TreeStoreData',{
extend: 'Ext.data.TreeStore',
model: 'TaskModel',
autoLoad: true,
autoSync: true,
proxy: {
type:'memory',
reader: {
type:'json'
}
},
root:dataObject.getData()
});
var treeStore = Ext.create('TreeStoreData');
Now I'm trying to update and display the value of this treestore on a button call which looks like this :
buttons:[
{
text:'Get CCP/Product',
handler:function (btn, evt) {
dataObject.print();
treeStore.removeAll();
dataObject.setData({'expanded':false,'children':[{'text':'Master11','expanded':true,'leaf':false,'children':[{'text':'Child 12','expanded':true,'leaf':false,'children':[{'text':'Child 23','expanded':true,'leaf':false,'children':[{'text':'Child 34','expanded':false,'leaf':false}]}]}]}]})
dataObject.print();
}
}
]
But on this button handler I'm always getting a "Uncaught TypeError: Cannot call method 'indexOf' of undefined " on treeStore.removeAll() method, where treestore is clearly defined in this context.
Question 1) What is the correct way to refresh a TreeStore ?
Answer 1)
Instead of:
treeStore.removeAll();
dataObject.setData( ... );
You should do:
dataObject.setData( ... ); // This won't affect the store
treeStore.setRootNode(dataObject.getData()); // Actually update the store
Note that changing dataObject's data won't affect the store automatically like you seem to think...
this code works for me (ExtJS 4.2.1)
Total tree panel nodes refresh example:
var responseDictObjects = $.ajax({
data: { Id: this.idDictionary },
dataType: "json",
type: "POST",
cache: false,
url: 'http://' + config.domain + '/' + 'api/Dictionaries/GetDictTreeData',
async: false
}).responseText;
responseDictObjects = jQuery.parseJSON(responseDictObjects);
while (this.storeDict.getRootNode().firstChild) {
this.storeDict.getRootNode().removeChild(this.storeDict.getRootNode().firstChild);
}
this.storeDict.getRootNode().appendChild(responseDictObjects.Data);
Replace this.storeDict with your store reference.
In my case:
JSON.stringify(responseDictObjects.Data)
returns
"[{"id":8,"text":"kkk","leaf":false,"expanded":true,"children":null},{"id":17,"text":"ttttt","leaf":false,"expanded":true,"children":null},{"id":22,"text":"gggg","leaf":false,"expanded":true,"children":null},{"id":23,"text":"qqq","leaf":false,"expanded":true,"children":null},{"id":24,"text":"fff","leaf":false,"expanded":true,"children":null},{"id":27,"text":"fff","leaf":false,"expanded":true,"children":null},{"id":28,"text":"ggggggggggggggggggg","leaf":false,"expanded":true,"children":null},{"id":31,"text":"ttttttttttt666666666","leaf":false,"expanded":true,"children":null},{"id":32,"text":"ffffffffffffffffffff","leaf":false,"expanded":true,"children":null},{"id":33,"text":"kkkkkkkkkkkkk","leaf":false,"expanded":true,"children":null},{"id":35,"text":"7777777777","leaf":false,"expanded":true,"children":null},{"id":36,"text":"999999999999","leaf":false,"expanded":true,"children":null},{"id":37,"text":"iii","leaf":false,"expanded":true,"children":null}]"
I found another bug with TreePanel, previosly removed nodes appears after executing appendChild. So i started to use jquery tree plugin (dynatree). All you need is to create empty panel. And after render a panel, embed tree, in my case:
Create empty panel:
that.treePanel = Ext.create('Ext.panel.Panel', {
title: 'Records',
width: 350,
height: 400
});
After rendering panel you can refresh nodes whenever you want:
var that = this;
var responseDictObjects = $.ajax({
data: { Id: this.idDictionary },
dataType: "json",
type: "POST",
cache: false,
url: 'http://' + config.domain + '/' + 'api/Dictionaries/GetDictTreeData',
async: false
}).responseText;
responseDictObjects = jQuery.parseJSON(responseDictObjects);
var el = this.treePanel.getId();
if (this.treeDict == null) {
this.treeDict = $('#' + el).dynatree({
onActivate: function (node) {
that.treeDict.lastSelectedId = node.data.index;
},
children: []
});
}
this.treeDict.dynatree("getRoot").removeChildren(true);
this.treeDict.dynatree("getRoot").addChild(responseDictObjects.Data);