How to get number of rows in datatable after ajax load - ajax

"ajax": {
"url": "<%=request.getContextPath()%>/Home?value=getreqs5",
"data": function ( json,callback) {
var oTable = $('#fifth').dataTable();
// Get the length
var count=oTable.fnGetData().length;
return json;
}
}
Ajax data is successfully loaded in datatable.But the number of rows showing zero. How can i get number of rows in datatable after ajax return data?

If you are using datatables 1.10 you can get the total rows number with
"ajax": {
"url" : "<%=request.getContextPath()%>/Home?value=getreqs5",
"dataSrc": function(res){
var count = res.data.length;
alert(count);
return res.data;
}
}
With the dataSrc you can get the ajax success callback. In this callback you can count the objects number than your Ajax returns.
If you want to know how many rows you have in all your Datatable including all rows in all pages you can do this in your datatables parameter but out your ajax parameter :
"initComplete": function(settings, json){
var info = this.api().page.info();
alert('Total records', info.recordsTotal);
}

Just adding for all people looking for how to get to the api in other usecases:
var table = $("#myTable").dataTable();
table.on('draw', function (data) {
console.log(table.page.info().recordsDisplay);
});

Related

Datatables Ajax call not displaying data

I'm using the datatables library to display some data and would like to update this every 30 seconds with data fetched form a URL. I've followed the api documentation and have implemented the code below to do this:
$( document ).ready(function() {
var table = $('#performance_summary').DataTable( {
ajax: 'https://myjasonurl.com'
} );
setInterval( function () {
table.ajax.reload();
}, 30000 );
});
When the page loads I can see that the correct URL is called to retrieve data, and data is returned in the correct format to display properly in the table (I've checked this works by loading this into the table directly). Unfortunately the resulting datatable when using the ajax call states that it is "loading" but never loads/shows the data, does anyone have any idea of how I fix this?
Try the DataTable().ajax.url function,
Following code works fine for me:
$(document).ready(function() {
var table = $('#performance_summary').DataTable({
paging: false,
searching: false,
ajax: "https://api.myjson.com/bins/897v1",
columns: [{
"title":"Test",
"data": "test"
}]
});
setInterval( function () {
$('#performance_summary').DataTable().ajax.url(
"https://api.myjson.com/bins/897v1"
).load();
}, 3000 );
});
here's the fiddle: https://jsfiddle.net/ju2bmtm7/84/

How to validate every record in the store by making an ajax call and checking its response Extjs

I have a panel with a header form and a detail form detail form consist of a grid and a form.
If the user clicks on save button which is in the header I have to take the value JDE present in the header as one parameter and check the REFNo present in each record present in the detailStore and make an ajax call.
If the data returned from the response is null I have to disable the save call.
Sample ajax call I am using in my code:
Ext.Ajax.request({
url: webContext + '/services/adjustment/accountsreceivableledger',
timeout: 120000,
method: 'GET',
params: {
addressNumber: jde,
documentNumber: r.data.customerInvoiceDebitNo
},
success: function(response) {
var returnedValue = Ext.decode(response.responseText);
if (returnedValue.data != null && returnedValue.data.length === 0) {
me.lookupReference('submit').disable();
Ext.Msg.alert('Submitting Error on Detail Reference number');
refValid = false;
me.getView().up('panel').ownerCt.unmask();
} else {
refValid = true;
}
return refValid;
}
});
Sample fiddle
Why don't you just concatenate all the ref numbers and pass to the server in one go?
var myRefParameter;
YourStore.each(function(r) {
if (myRefParameter!='')
myRefParameter +='|';
myRefParameter += r.get('RefField');
});
Ext.Ajax.request({
url: webContext + '/services/adjustment/accountsreceivableledger',
timeout: 120000,
method: 'GET',
params: {
addressNumber: jde,
documentNumber: myRefParameter //Pass it here
},
...........
Just split the Ref. Numbers on the server and do all the necessary validations.
As per your requirement,
I need to check all the return responses and if the response data is not null or Empty then only submit the call
For this you need to create a common ajax call function and call this function on save button for every record as present on store. You have to maintain one array for customerInvoiceDebitNo and one ajaxcount to check all response. You need to put bellow code on your save button click event.
You can modify below code basis of your requirement.
Code Snippet
var customerInvoiceDebitNo = '',
allCustomerInvoiceDebitNo = [],
ajaxCount = 0;
detailStore.each(function(r) {
customerInvoiceDebitNo = r.get('customerInvoiceDebitNo');
if (customerInvoiceDebitNo !== 0 && detlview.getViewModel().get('currentHeader').data.sourceDocuments[0].documentNumber !== customerInvoiceDebitNo) {
//call ajax request for per record
doApiCall({
addressNumber: jde,
documentNumber: customerInvoiceDebitNo
});
//Push customer invoice debit no in Array for checking response in Ajax request success.
allCustomerInvoiceDebitNo.push(customerInvoiceDebitNo);
//For checking number of ajax call.
ajaxCount++;
}
});
//This function will make ajax call for per record
function doApiCall(data) {
Ext.Ajax.request({
url: webContext + '/services/adjustment/accountsreceivableledger',
timeout: 120000,
method: 'GET',
params: data,
customerInvoiceDebitNo: data.customerInvoiceDebitNo,
success: function(response) {
ajaxCount--;
//When All ajax request response will get then unmask on view
if (ajaxCount == 0) {
me.getView().up('panel').ownerCt.unmask();
}
var returnedValue = Ext.decode(response.responseText);
if (returnedValue.data != null && returnedValue.data.length === 0) {
//Remove this current customerInvoiceDebitNo from array if response is not null.
Ext.Array.remove(allCustomerInvoiceDebitNo, this.customerInvoiceDebitNo);
//Initially submit button will be disable
//If all ajax request response is not null then array will be empty then we can make sumit button enable.
if (Ext.isEmpty(allCustomerInvoiceDebitNo)) {
}
}
}
});
}
//Initially submit button will be disable
//This function will enable submit button when all request reponse will not null or empty.
function doEnableSumbitButton() {
me.lookupReference('submit').setDisabled(false);
}
I hope this will guide or help you to achieve your requirement.

How to display the corresponding table value of the response in AJAX

I have an ajax response that is equal to 1. And,in my success function, I want to display not the 1 to my view but the corresponding column_name which is 'brands_name' in the brands table which is 'Apple' in this case. I want to display this after a successful post request. Any ideas?
You need to send your response from your controller (json)
// controller
$data['ajax_response'] = 1;
$data['brands_name'] = $brands_name;
return json_encode($data);
You need to catch the success function to get the variable you want from php
// javascript
$.ajax({
url:link,
dataType:"json",
data:data,
type:"post",
success: function(data)
{
if(data.ajax_response == 1)
{
console.log(data.brands_name);
}
},
error: function()
{
}
});

Kendo Datasource response is empty

I am new to Kendo UI. I am trying to read the remote data and display in the screen. I am able to see the remote json data by accessing the URL in the browser. But when I try to alert() the response data inside kendo UI, it is empty.
here is the sample code.
<script type="text/javascript">
var shareDataSource;
var viewModel;
function searchByVin() {
var vin = $("#vinNumber").val();
shareDataSource = new kendo.data.DataSource({
transport: {
read: {
url: "http://localhost:9080/portal/programexcep/resources/request/vin/"+vin,
dataType: "json"
}
},
schema: {
data: "data",
model: { id: "Id" }
},
requestEnd: function(e) {
var response = e.response;
var type = e.type;
alert(type);
alert(response.length);
}
});
shareDataSource.read();
alert(vin);
alert(kendo.stringify(shareDataSource.data()));
}
</script>
The JSON data is
{"Id":10,"FirstName":"John Smith","vin":"html5"}
as the response in the browser. The alert(kendo.stringify(shareDataSource.data())); is empty
and the alert(response.length); is also undefined.
Can someone help on this?
The problem is that shareDataSource.read(); is asynchronous which means that you invoke read but data is not immediately available. You can use fetch instead that executes a portion of code when the data is available. Your code would be:
shareDataSource.fetch(function() {
alert(vin);
alert(kendo.stringify(shareDataSource.data()));
});
There is also a problem in requestEnd function: you try to get the length of response but in the model definition you say that data field is called data so your server should be returning something like:
{
"data" : [
{ "Id" : 1 },
{ "Id" : 2 },
{ "Id" : 3 }
]
}
and then for accessing the length you should do response.data.length

Call Ajax Get function inside mRender Datatable

I am looking to call an ajax function inside the Datatables mRender function that will use an id from the present ajax source to get data from a different ajax source.
To put this into perspective, I have:
A listing of requisitions from different clients in one Datatable.
In this listing I have a client id. I want to get the client Name to be shown on the table instead of the client Id. However the Client Name and other client details are in the clients table hence these details are not in the requisitions json data. But I have the Client Id.
How do I use this to get client name inside the mrender function? E.g
{"sTitle":"Client","mData":null,
"mRender":function(data){
//ajax function
}
},
Thank you in advance,
Regards.
I don't believe this is how you are supposed to deal with your data. However I also use an AJAX data source in my mRender function as stated below.
$(document).ready(function(e){
$('.products').dataTable({
"bProcessing": true,
"sAjaxSource": window.location.protocol + "//" + window.location.hostname + '/product/getAll',
"aoColumns": [
{ "sTitle": "Pid", "bVisible" : false},
{ "sTitle": "Pname" },
{ "sTitle": "Pprice" },
{ "sTitle": "Pgroups",
"mRender" : function( data, type, full ){
console.log( data, type, full );
console.log(category.getAll());
return 'test';
}
}
]
});
});
De category object is initialized in a selfinvoking function. I used this to prevent the function from loading the data remotely each time the function is called.
It looks like this:
(function(){
if(typeof category === 'undefined'){
category = {};
}
category.getAll = function(){
if(typeof category.all === 'undefined'){
$.ajax({
'type' : 'POST',
'async': false,
'url' : window.location.protocol + "//" + window.location.hostname + "/category/getAll",
'success' : function(data){
console.log(data);
category.all = data;
},
'error': function(a,b,c){
console.log("You shall not pass!",a,b,c);
alert('stop');
}
});
}
return category.all;
}
})();

Resources