jQuery datatable generic ajax call - javascript

I am using jQuery datatables with the following code:
$table.DataTable({
lengthMenu: [10, 25, 50, 100],
processing: true,
paging: true,
ajax: {
type: "GET",
url: '',
data: function(d) {
},
dataSrc: function(json) {
//some logic
return json.items;
},
error: function(jqXHR) {
}
},
"columns": [//my columns]
});
What I want is to make the ajax request generic like below:
$table.DataTable({
lengthMenu: [10, 25, 50, 100],
processing: true,
paging: true,
ajax: ajaxForDataTable(url, methodType, function (d) { }, dataSrcCallback),
"columns": [//my columns]
});
function ajaxForDataTable(url, methodType, dataCallback, dataSrcCallback) {
$.ajax({
type: methodType,
url: baseUrl + url,
data: dataCallback,
dataSrc: dataSrcCallback,
error: function (jqXHR) {}
});
}
function dataSrcCallback() {
}
The above code is working fine and getting response from the server but the dataSrcCallback never called (where I am manipulating data) so the datatable never populates with the data (empty). As I am using this table on multiple pages, if I change any logic I have to do it on all the pages. Can anybody tell me what I am doing wrong over here so I can rectify it and make it works for me?

Take a look at the docs: https://datatables.net/reference/option/ajax .
You're suppose to pass a function to the ajax parameter and call the callback method with the data you want to pass to the datatable.
$('#example').dataTable( {
"ajax": function (data, callback, settings) {
callback(
JSON.parse( localStorage.getItem('dataTablesData') )
);
}
} );

Related

I failed to refresh data in yajra/laravel-datatables-oracle with draw method

In laravel 6 app I use "yajra/laravel-datatables-oracle": "^9.4" and I need selecting 1 row and running ajax request on server to delete this row
I try to refresh table with draw() method and it does not work.
In my blade file :
#push('scripts')
var oTable;
$(document).ready(function () {
oTable = $('#my_tasks_data').DataTable({
processing: true,
serverSide: false,
info: false,
order: [],
});
$('div.dataTables_length select').select2({
theme: "bootstrap"
});
...
function taskComplete(rowId) {
$.ajax({
url: 'tasks/' + rowId + '/complete',
type: "post",
dataType: 'json',
data: {'_token': '{{csrf_token()}}'},
success: function (data) {
console.log('taskComplete success data::')
console.log(data)
console.log('oTable::')
console.log(oTable)
oTable.draw(); // THat does not work
alert( 'AFTER::' )
},
error: function (xhr) {
console.error(xhr)
}
});
}
I check oTable var and see : https://prnt.sc/ujyp14 It looks like valid Table object
Why it does not work and how it can be fixed?
Thanks!
I found decision with setting serverSide property to true
oTable = $('#my_tasks_data').DataTable({
processing: true,
serverSide: true,
and after that method oTable.draw() works ok

Reload DATATABLE inside AJAX success without refreshing page

I have a table using Datatable plugin. I have filtered what I want to delete and after deletion, I manage to empty the value.
After that, if I want to filter using the same text again, for example, I have ba 1 and ba 2 and after deleting ba 1, it still shows the cell when I entered ba on the filter textarea field. It suppose to display the remaining ba which are not deleted yet.
For your information, I'm not using built in Datatable Ajax method.
what I'm trying to do is I want it to reload the table with the new data without refreshing the page after ajax on success. How to do that?
My datatable :
var table1 = $('#table1').DataTable(
{
pageLength : 500,
lengthChange: false,
deferRender: true,
scrollY: 800,
scrollCollapse: true,
scrollX: true,
bSort: false,
cache: true,
autoWidth: false,
columnDefs: [
{
targets: 0,
checkboxes:
{
selectRow: true
}
}
],
select: {
style: 'multi',
selector: 'td:not(:nth-child(4), :nth-child(5), :nth-child(6), :nth-child(9), :nth-child(10), :nth-child(13), :nth-child(14), :nth-child(15), :nth-child(16), :nth-child(17), :nth-child(18), :nth-child(19), :nth-child(20), :nth-child(21), :nth-child(22), :nth-child(23), :nth-child(24), :nth-child(25))'
}
});
Here's my filtering function code :
table1.columns().every(function ()
{
var table = this;
$('.filter', this.header()).on('keyup change', delay(function (settings, data, dataIndex)
{
if (table.search() !== this.value)
{
table.search(this.value).draw();
}
}, 500));
});
Here's my AJAX success code for deletion based on selected checkbox:
$('.btnN2').click(function(){
var answer = confirm('Delete N2 : Are you sure you want to delete selected items?');
if (answer)
{
console.log('yes');
var rows = $(table1.rows({selected: true}).$('input[type="checkbox"]').map(function()
{
return $(this).prop("checked") ? $(this).closest('tr').attr('data-getstockcode') : null;
}));
var getstockcodes = [];
$.each(rows, function(index, rowId)
{
console.log(rowId)
getstockcodes.push(rowId);
});
$.ajax({
url: 'del_n2',
type: 'GET',
data: {"getstockcodes": JSON.stringify(getstockcodes)},
dataType: 'JSON',
success:function(data){
console.log(data);
$(table1.rows({selected: true}).$('input[type="checkbox"]').map(function()
{
if($(this).prop("checked"))
{
$(this).parents("tr:eq(0)").find(".note2").val('');
console.log('reset');
}
}));
}
});
}
else
{
console.log('cancel');
}
});
Here's my insert data based on keyup event
$(".note2").keyup(delay(function()
{
var stockcode = $(this).data("stockcode");
var stockname = $(this).data("stockname");
var value = $(this).val().replace(/(\r\n|\n)/g, "\\n");
$.ajax({
url: 'saveNote2',
type: 'GET',
data: 'stockcode='+stockcode+'&stockname='+stockname+'&value='+value,
dataType: 'JSON',
success: function(data){
console.log(data);
},
error: function(data){
console.log(data);
}
});
}, 300));
Just add this in your success function
table1.ajax.reload()
If you are using ajax datatable or local you need to make it like this
table1.clear();
table1.rows.add(your response data array);
table1.draw()

Ajax error on datatable initialisation on table within modal

I have a modal with a search box within it, which when the search button is hit, has an ajax call which goes to the controller, which then returns a table of results, which is then put into a div. Like so:
$.ajax({
url: url,
data: JSON.stringify(viewModel),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
cache: false,
type: "POST",
success: function (result) {
if (result.success === true) {
$("#searchResultsPlaceHolder").show();
$("#searchResultsPlaceHolder").html(result.view, function() {
var noOfRows = $('#searchResultsTable tr').length;
if (noOfRows > 1) {
loadSearchDatatable();
}
});
}
},
error: function (responseText, textStatus, errorThrown) {
alert('Error - ' + errorThrown);
}
});
All that is fine, and works perfectly up until I try to make it a datatable. If I take out the lines
$("#searchResultsPlaceHolder").html(result.view, function() {
var noOfRows = $('#searchResultsTable tr').length;
if (noOfRows > 1) {
loadSearchDatatable();
}
});
and just have
$("#searchResultsPlaceHolder").html(result.view)
it works fine, it gives me a table with my results. But as this is in a modal, and the returned results may get quite lengthy, I want to use a datatable to implement pagination and sorting. But whenever I apply the loadSearchDatatable function to the table after the div is populated with the returned html, I get the error:
table id=searchResultsTable - Ajax error
The datatable actually appears, with the sort buttons and paging buttons present, but none of them do anything, and the table is longer than the length I specified (5). Here is my datatable function:
function loadSearchDatatable() {
$('#searchResultsTable').dataTable({
ajax: "data.json",
"bLengthChange": false,
'iDisplayLength': 5,
"bSort": true,
"sPaginationType": "full_numbers",
"bFilter": false,
"sDom": 'ft<"bottom"ilp>',
"bDestroy": false,
"aaSorting": [[0, "asc"]]
});
};
Does anyone have any idea how to fix this error?
Use the code below instead:
$("#searchResultsPlaceHolder").html(result.view);
var noOfRows = $('#searchResultsTable tr').length;
if (noOfRows > 1) {
loadSearchDatatable();
}
Also remove ajax: "data.json", in your function loadSearchDatatable().

Get data from controller in json form inside a datatable

Here's the case.
I am using ajax call in datatable js to bind json data in my table.
Right now I am using directly json file for databinding.
Now I want to access the data from my db for which I have written a
method inside my controller which returns json value.
But I am not able to call this method like I was calling my json file
in ajax. Kindly suggest the solution.
Below are the code sample
var table = $('#example').DataTable({
"ajax": "/content/data/dataList.json", //here I want the url of my method.
"bDestroy": true,
"iDisplayLength": 15,
"columns": [
{
"class": 'details-control',
"orderable": false,
//"data": null,
"defaultContent": ''
},
{ "data": "name" },
],
"order": [[1, 'asc']],
"fnDrawCallback": function (oSettings) {
runAllCharts();
}
});
And my method id :
//Controller Name AppDetail
public string getData(string ddlid)
{
DataTable ddl = new DataTable();
string query = string.Empty;
if (ddlid == "O1")
{
query = "SELECT for O1";
}
else if (ddlid == "O2")
{
query = "SELECT for O2";
}
con.Open();
MySqlDataAdapter da = new MySqlDataAdapter(query, con);
da.Fill(ddl);
con.Close();
System.Web.Script.Serialization.JavaScriptSerializer jSearializer = new System.Web.Script.Serialization.JavaScriptSerializer();
return jSearializer.Serialize(ddl);
}
And here is the json data sample
{
"data": [
{
"name": "Aladdin"
}
]
}
Kindly Help.
if you are not using server side processing method get all data first using ajax method and use that data on data table. look at the code below... it might help you for getting some idea.
$.ajax({
url: 'api/AppDetail/getData',
method: 'get',
data :{ddlid:'01'}, // this is input parameter for your function
dataType: 'json',
contentType: 'text/json',
success: function(res){
var table=$('#example').dataTable({
data: res,
columns:[
{'data':'name'}
],
bDestroy : true,
iDisplayLength : 15,
});
}
});
If your controller works you can call it before DataTables and insert the data via the data (https://datatables.net/reference/option/data) source of DataTables
On the Controller if u are getting Data which u want, then u can return this Data to a partial view.
Note that the partial view is nothing a html table which u bulild upon Razor syntax or anything.
Then make ajax call to return this partial view, On success u can apply data table plugin.
<div id=MyTable></div>
$.ajax({
type: 'GET',
url: ControllerName/ActionName=partialView Which makes table.
success: function (data) {
debugger;
$('#MyTable').html(data); //Puting result of ajax call to the div which containg Id,
$('#PartilView_Table').DataTable({ // Applying DataTable Plugin table inside partialView
"bProcessing": true,
"bDeferRender": true,
"scrollX": true,
"stateSave": true,
"bAutoWidth": true,
"bSort": false,
"columnDefs": [
{
}
]
});
},
});
Hope this will help you..

Kendo UI, datagrid inserted row produces request multiple times

i have problem with Kendo data grid component.
I'm trying to add new row into grid and create remote request to API via create event.
Problem is that if i try to add new row after first request Kendo make 2 requests instead of the one.
I tried to find some solution for this using transport create and options.success method but without luck.
http://docs.telerik.com/kendo-ui/api/framework/datasource#configuration-transport.create
Could somebody tell to me what i'm doing wrong?
Thanks for any help.
Here is the code of the server response for create:
+ Response 200 (application/json)
{
"status": "OK",
"result":[
{
"id":22,
"username":"blahblah",
"name":"Thomas",
"surname":"Man",
"email":"to.mas.marny#gmail.com",
"created":"1399986964",
"role":"USER"
}
]
}
Here is the code of the method:
$scope.initGrid = function () {
// get access token from localstorage
var token = localStorage
.getItem($rootScope.lsTokenNameSpace);
// set pagination data
var paginationData = {
"token": token,
"data": {
"page": 1,
"items_per_page": 20
}
};
var dataPacket;
dataPacket = new kendo.data.DataSource({
transport: {
read: function (options) {
$.ajax({
url: $rootScope.apiBaseUrl + "user/list",
dataType: "json",
type: "POST",
data: JSON
.stringify(paginationData),
success: function (
response) {
console
.log("List of users succesfully obtained");
console
.log(response.result);
// pass response to
// model
options
.success(response);
// $notification.enableHtml5Mode();
},
error: function (error) {
console
.log("user list request error");
console.log(error);
$notification
.error(
"User list cannot be loaded",
"Please try again in a minute.");
}
});
},
update: function (options) {
console.log("Update");
options
.success("{\"test\":\"test\"}");
},
destroy: function (options) {
console.log("destroy");
options
.success("{\"test\":\"test\"}");
},
create: function (options) {
console.log("Create");
console.log(options.data);
$.ajax({
url: $rootScope.apiBaseUrl + "user/create",
dataType: "json",
type: "POST",
data: JSON
.stringify(options.data),
success: function (
response) {
console
.log("New user created");
console
.log(response.status);
// pass response to
// model
options
.success(response.result);
// $notification.enableHtml5Mode();
},
error: function (error) {
console.log("user list request error");
console.log(error);
$notification
.error(
"User cannot be created",
"Please try again in a minute.");
}
});
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {models: kendo.stringify(options.models)};
}
}
},
//batch : true,
//autoSync: true,
schema: {
data: "result",
model: {
id: "id",
fields: {
id: {
editable: false,
nullable: true
},
name: {
editable: true,
nullable: false
},
username: {
editable: true,
nullable: false
}
}
}
}
});
$("#grid").kendoGrid({
dataSource: dataPacket,
filterable: true,
pageSize: 20,
pageable: true,
height: 550,
toolbar: ["create", "save", "cancel"],
columns: ["id", "name", "username", {
command: ["edit", "destroy"],
title: " ",
width: "200px"
}],
editable: "inline"
});
};
If you declare id inside model then you don't have to declare id inside model fields.
Also when you point
data: "result"
for the model you have to pass
options.success(response)
inside ajax's success function, not just
options.success(response.result)
I think if null is passed to the Datasource of the kendo Grid in the html helper, the Grid will be built in “remote data mode” rather than “local data mode”
and since the read Url is not set the current browser Url will be used for the read operation.
make sure to initialize the list in the Model before using it as a Datasource.

Categories

Resources