DataTables do not send ajax request at the initialization - javascript

How to use dataTables to instantiate the table does not load data (server mode),then loading data when i click on a button.If serverSide is set to true at initialization, the table will automatically send an ajax request, then render the data, which is not what I want !:(

You should use "iDeferLoading" : 0 in DataTables parameters, when you initialize it:
var table = $("#table").dataTable({
"bProcessing": true,
"bServerSide": true,
"iDeferLoading": 0,
"sAjaxSource": service_url,
"sServerMethod": "POST",
...
...
(or "deferLoading":0 for newer DataTables versions, 1.10 and above),
and then add the event to your button:
$("#button").on("click", function (event) {
$('#table').dataTable().fnDraw();
});
https://datatables.net/examples/server_side/defer_loading.html

in a similar situation, this is how I did it.
<script>
$(function ($) {
$("#tbl").DataTable({columns:[{data:"id"}, {data:"text"}], dom: "tB", buttons: [{ text: "Load Me", action: function (e, dt, node, config) { loadme(e, dt, node, config); } }] });
}
);
// // parameters are passed from the datatable button event handler
function loadme(e, dt, node, config) {
parms = JSON.stringify({ parm1: "one", parm2: "two" });
$.ajax({
// my test web server that returns an array of {id:"code field", text:"country namee"}
url: "WebService1.asmx/GetAList",
data: JSON.stringify({ s: parms }),
type: 'post',
contentType: "application/json; charset=utf-8",
dataType: "json",
// this is just away of passing arguments to the success handler
context:{dt:dt, node:node},
success: function (data, status) {
var contries = JSON.parse(data.d);
for (var i = 0; i < contries.length; i++){
this.dt.row.add(contries[i], "id", "text");
this.dt.draw();
}
},
error: function (one, two) {
debugger;
}
});
}
</script>
</head>
<body>
<div style="width:500px">
<table id="tbl">
<thead>
<tr>
<th>Code</th>
<th>Contru</th>
</tr>
</thead>
<tbody></tbody>
<tfoot></tfoot>
</table>
</div>
</body>

After looking at the source code for half a day, I finally found a solution. First I needed a custom parameter called firstAjax and set it to false. like this:
$("#example").DataTable({
serverSide: true,
ajax: {
url: 'your url'
},
firstAjax: false
});
Then I changed the
_fnReDraw (settings); //in datatables.js line 4717
to
if (settings.oInit.firstAjax) {
_ fnReDraw (settings);
}
If the compressed js file(datatables.min.js), you should find _fnReDraw function corresponding alias.

I found the solution, in the initialization make like this, with the "oLanguage":
$('.table').dataTable({
oLanguage: {
sUrl: ""
}
});

After initialize datatables with ajax, use this simple line to call ajax for get data:
$('#table').DataTable().ajax.reload();
this code may not working with old versions of datatables.
Download latest version: https://datatables.net/download

Related

After jQuery Ajax invocation call , the application Fails to navigate to the ASP.NET MVC view that I want to show

I'm using jquery DataTables to show some tabular data, and I also placed an edit link for each row in said jquery DataTables so that the user can edit data associated with a particular row if needed. ( Also, I have No clue how to use ASP.NET MVC Html helpers within jQuery DataTables so that is why I am using the html link in the following code )
jquery DataTable javascript:
$("#resultCodeTable").dataTable({
"processing": true,
"serverSide": false,
"destroy": shouldDestroy,
"ajax": {
"url": "../Admin/LoadResultCodes",
"type": "GET",
"datatype": "json",
"data": function (data) {
data.actionCodeIDArg = actionCodeIDInQuestion;
}
},
....................................
............................
..............
columnDefs: [
{
{
targets: 1,
searchable: false,
orderable: false,
name: "EditResultCodeInQuestionReasonForArrears",
"data": "ID",
render: function (data, type, full, meta) {
if (type === 'display') {
data = '<a class="editResultCodeInQuestionReasonForArrears" href="javascript:void(0)" data-id="' + full.ID + '">Edit RFAs</a>'
}
return data;
}
},
....................................
............................
..............
Clicking on the aforementioned link will ensure that the point of execution reaches the following jQuery Event Handler method:
jQuery Event handler method/ function Javascript
$('#resultCodeTable').on('click', '.editResultCodeInQuestionReasonForArrears', function () {
console.log(this.value);
navigateToAParticularResultCodeAssociatedReasonForArrearsList($(this).data('id'));
});
The jQuery Ajax call successfully invokes the C# Controller's action because I see the Visual Studio's Debugger's point of execution reach said Controller's action, however, it fail to navigate to the view that I want to show.
jquery / javascript:
function navigateToAParticularResultCodeAssociatedReasonForArrearsList(resultCodeTable_ID) {
console.log(resultCodeTable_ID);
$.ajax({
url: '../Admin/NavigateToAParticularResultCodeAssociatedReasonForArrearsList',
type: 'POST',
dataType: 'json',
contentType: "application/json;charset=utf-8",
data: "{'" + "resultCodeTable_IDArg':'" + resultCodeTable_ID + "'}",
cache: false,
}).done(function (response, status, jqxhr) {
})
.fail(function (jqxhr, status, error) {
// this is the ""error"" callback
});
}
C#: ( in my AdminController.cs )
public ActionResult NavigateToAParticularResultCodeAssociatedReasonForArrearsList(int resultCodeTable_IDArg)
{
AParticularResultCodeAssociatedReasonForArrearsListViewModel aParticularResultCodeAssociatedReasonForArrearsListViewModel = new AParticularResultCodeAssociatedReasonForArrearsListViewModel();
aParticularResultCodeAssociatedReasonForArrearsListViewModel.ResultCodeTable_ID = resultCodeTable_IDArg;
return View("~/Areas/Admin/Views/Admin/AdminModules/Auxiliaries/AParticularResultCodeAssociatedReasonForArrearsList.cshtml", aParticularResultCodeAssociatedReasonForArrearsListViewModel);
}
Razor / Html: (In my \Areas\Admin\Views\Admin\AdminModules\Auxiliaries\AParticularResultCodeAssociatedReasonForArrearsList.cshtml view )
#model Trilogy.Areas.Admin.ViewModels.Auxiliaries.AParticularResultCodeAssociatedReasonForArrearsListViewModel
#{
ViewBag.Title = "AParticularResultCodeAssociatedReasonForArrearsList";
}
<h2>AParticularResultCodeAssociatedReasonForArrearsList</h2>
Could someone please tell me how I can change the code so that the view shows up after the jquery Ajax invocation?
May be on .done function you will get the view in the response, you need to take that response and bind it to your control
You call the controller via AJAX, and sure it hits the controller action method, and the controller returns a view but this is your code that deals with whatever is returned from the AJAX call (from the controller):
.done(function (response, status, jqxhr) {})
You are doing absolutely nothing, so why would it navigate anywhere.
A better question you need to ask yourself, instead of fixing this, is why would you use AJAX and then navigate to another page. If you are navigating to a whole new page, new URL, then simply submit a form regularly (without AJAX) or do it via a link (which the user will click). Use AJAX post if you want to stay on the same page and refresh the page's contents.
#yas-ikeda , #codingyoshi , #code-first Thank you for your suggestions.
Here are the modifications that I had to make to resolve the problem(please feel free to suggest improvements):
Basically, I had to end up creating 2 separate Action methods to resolve the problem.
In the jquery/Javascript code below, it is important to note the first action method '../Admin/RedirectToNavigateToAParticularResultCodeAssociatedReasonForArrearsList'
function navigateToAParticularResultCodeAssociatedReasonForArrearsList(resultCodeTable_ID) {
console.log(resultCodeTable_ID);
$.ajax({
url: '../Admin/RedirectToNavigateToAParticularResultCodeAssociatedReasonForArrearsList',
type: 'POST',
dataType: 'json',
contentType: "application/json;charset=utf-8",
data: "{'" + "resultCodeTable_IDArg':'" + resultCodeTable_ID + "'}",
cache: false,
}).done(function (response, status, jqxhr) {
window.location.href = response.Url;
})
.fail(function (jqxhr, status, error) {
// this is the ""error"" callback
});
}
The purpose of the 1st action method called '../Admin/RedirectToNavigateToAParticularResultCodeAssociatedReasonForArrearsList' is to retrieve a url within a Json object.
[HttpPost]
public ActionResult RedirectToNavigateToAParticularResultCodeAssociatedReasonForArrearsList(int resultCodeTable_IDArg)
{
var redirectUrl = new UrlHelper(Request.RequestContext).Action("NavigateToAParticularResultCodeAssociatedReasonForArrearsList", "Admin", new { resultCodeTable_IDArg = resultCodeTable_IDArg });
return Json(new { Url = redirectUrl });
}
The purpose of the 2nd action method is to ultimately navigate to the ASP.NET MVC View that I want to show.
public ActionResult NavigateToAParticularResultCodeAssociatedReasonForArrearsList(int resultCodeTable_IDArg)
{
AParticularResultCodeAssociatedReasonForArrearsListViewModel aParticularResultCodeAssociatedReasonForArrearsListViewModel = new AParticularResultCodeAssociatedReasonForArrearsListViewModel();
aParticularResultCodeAssociatedReasonForArrearsListViewModel.ResultCodeTable_ID = resultCodeTable_IDArg;
aParticularResultCodeAssociatedReasonForArrearsListViewModel.RFACodeList = actionCodeResultCodeBusinessService.GetSpecificResultCodeRFACodeList(resultCodeTable_IDArg);
return View("~/Areas/Admin/Views/Admin/AdminModules/Auxiliaries/AParticularResultCodeAssociatedReasonForArrearsList.cshtml", aParticularResultCodeAssociatedReasonForArrearsListViewModel);
}
However, I Dislike the fact that I have to use 2 action methods to navigate to the desired asp.net mvc view, therefore, please feel free to suggest improvements or even a totally different better solution.

How to prevent pagination reset in datatable using ajax

TLDR;
How to stay on the page in datatable using ajax my way?
My problems
User click a button in the table. That particular row will be updated and I will call the fn_GetData() function.
I will fetch the updated data from database into the table again, thus updating the row (actually entire table was updated).
If the row is few page later, when the table reload, it will back to the first page again. How to remain on that particular page?
Btw I tried .ajax.reload( null, false ) is not working
Ajax wrapped in javascript function
function fn_GetData(){
$.ajax({
url: "action/myfile.php",
type: "POST",
data: {'GetData':''},
dataType: "json",
success: function(data) {
if(data.status=='success'){
if ($.fn.DataTable.isDataTable("#myTable")) {
$('#myTable').DataTable().clear().destroy();
}
var myTable = $('#myTable').html(data.table).DataTable({
responsive: {
details: {
type: 'column'
}
},
"dom": 'Bplirtip',
}).columns.adjust().responsive.recalc();
//myTable.ajax.reload( null, false );
}
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr);
}
});
}
Enable state saving:
$('#example').dataTable( {
stateSave: true
} );

Appending Rows to a DataTables Grid

I'm trying to add <tr/> tags dynamically to a DataTable, but I didn't find actual good documentation on how the "adding TR process" is supposed to work. I have this as my DataTables setup:
$("#Grid").DataTable({
stateSave: true,
fixedHeader: true,
rowReorder: true,
.
.
columnDefs: [
{ orderable: false, className: "seq-cell", targets: 0 },
{ orderable: false, targets: "_all" }
]
})
.on("row-reordered", function (e, diff, edit) {
for (var i = 0; i < diff.length; i++)
{
..
}
});
I'm getting the definition of the item in the grid from an MVC action method as an HTML string, via a jQuery AJAX statement:
$.ajax({
type: "post",
url: "AddItem",
data: $("#newitemform").find(":input[name]").serialize(),
success: function (d) {
var $body = $("#Grid tbody");
$body.append(d);
}
});
The "d" parameter is the HTML for a row; I'm appending it to the body. That adds correctly and but doesn't have the row reorder functionality enabled then. What is the proper way to append to a DataTable, then re-enable whatever functionality?
Use row.add() API method to add a new row instead of appending to the table body.
If d contains string in the following format <tr>...</tr>, you could just use $("#Grid").DataTable().row.add($(d).get(0)) to add a new row.
For example:
$.ajax({
type: "post",
url: "AddItem",
data: $("#newitemform").find(":input[name]").serialize(),
success: function (d) {
$("#Grid").DataTable().row.add($(d).get(0)).draw();
}
});
See this example for code and demonstration.
The best option is to use Datatables API's to add rows to the table. As indicated in the previous response you can use either row.add() or rows.add(). The data needs to be in a data structure that matches your Datatables data structure config, ie, arrays or objects.
However it looks like you are receiving HTML structured data and appending directly to the table. In this case Datatables is not aware of the added data. You will need destroy (destroy()) the Datatables table, append your data then re-init Datatables. For example:
$.ajax({
type: "post",
url: "AddItem",
data: $("#newitemform").find(":input[name]").serialize(),
success: function (d) {
$("#Grid").DataTable().destroy();
var $body = $("#Grid tbody");
$body.append(d);
$("#Grid").DataTable({
stateSave: true,
fixedHeader: true,
rowReorder: true,
.
.
columnDefs: [
{ orderable: false, className: "seq-cell", targets: 0 },
{ orderable: false, targets: "_all" }
]
})
}
});

ajax success function not working on datatable

I'm using datatable to show list from database mysql
I need to update some input on end of table loading, then I'm using success function but this seems to prevent data rendering
var table = $('#example').DataTable({
'processing': true,
'serverSide': true,
'ajax': {
type: 'POST',
'url': url,
'data': function (d) {
console.log(d.order);
return JSON.stringify( d );
},
// EDIT this "my" success function
success: function( data ) {
$('#my_input').val(data.return);
}
}
Json returned is:
{
"data":[[ (datatable value) ]],
"returned":"myvalue"
}
here the jsfiddle
EDIT
http://jsfiddle.net/ntcwust8/95/
Datatable has its own complete event thats called initComplete.
If you redefine success you are overriding Datatable's own function.
var table = $('#example').DataTable({
'processing': true,
'serverSide': true,
'ajax': {
....
....
},
'initComplete':function(settings, json){
alert($('#example tbody tr').length+ ' records on screen');
});
Reference: https://datatables.net/reference/option/initComplete
Update fidle: http://jsfiddle.net/ntcwust8/94/
Just remove the success callback.
success - Must not be overridden as it is used internally in
DataTables. To manipulate / transform the data returned by the server
use ajax.dataSrc (above), or use ajax as a function
Datatable by default handles the success callback, Don't override it.
Instead use complete option of AJAX to do something after data loading.
Updated fiddle
You just need to remove success callback.
var table = $('#example').DataTable({
'processing': true,
'serverSide': true,
'ajax': {
type: 'POST',
'url': url,
'data': function (d) {
console.log(d.order);
return JSON.stringify( d );
}
}
Edit
you need to use ajax.dataSrc property it will call after ajax finish.
It will work on refresh as well
https://datatables.net/reference/option/ajax.dataSrc
var table = $('#example').DataTable({
'ajax': {
type: 'POST',
'url': url,
'data': function (d) {
console.log(d.order);
return JSON.stringify( d );
},
"dataSrc": function (json) {
$("#mydata").val(json.recordsTotal);
return json.data;
}
},
});
here is updated fiddle.
http://jsfiddle.net/2jkg3kqo/2/

Datatables won't reload json data

Not only should this be a straightforward operation but I'm following the documentation as well. I have an ajax call that returns a json data set. I've cleared the table successfully but when the success method is called nothing happens. The console statement shows that data is being returned... however the table remains empty. Any idea why?
JS
$('#SortByCoverage').click(function () {
var table = $('#theTable').DataTable();
table.fnClearTable();
$.ajax({
url: '/Home/Question2',
type: 'GET',
dataType: 'json',
success: function (data) {
console.log(data);
$("#thetable").dataTable({
"aaData": data,
"aoColumns": [
{title:"AdId"},
{title:"BrandId"},
{title:"BrandName"},
{title:"NumPages"},
{title:"Position"}
]
});
}
});
Server Side Code
public JsonResult Question2()
{
var ads = _client.GetAdDataByDateRange(new DateTime(2011, 1, 1), new DateTime(2011, 4, 1));
var json = ads.Where(x => x.Position.Equals("Cover") && x.NumPages >= (decimal)0.5).Select(x => new{
AdId = x.AdId,
BrandId = x.Brand.BrandId,
BrandName = x.Brand.BrandName,
NumPages = x.NumPages,
Position = x.Position
});
return Json(json, JsonRequestBehavior.AllowGet);
}
Sample Data (client side)
EDIT
As pointed out in the comments I misspelled the element name dataTable in the success callback. However, now I'm getting the following error:
Cannot reinitialise DataTable. To retrieve the DataTables object for this table, pass no arguments or see the docs for bRetrieve and bDestroy
Do I really have to destroy the table, once it's clear, to reload the data?
I added the bRetrieve and bDestroy. This got rid of the error but still no new data loaded into the table.
$.ajax({
url: '#Url.Action("Question2", "Home")',
type: 'GET',
dataType: 'json',
success: function (data) {
console.log(data);
$("#theTable").dataTable({
//"bRetrieve": true,
"bDestroy": true,
"aaData": data,
"aoColumns": [
{title:"AdId"},
{title:"BrandId"},
{title:"BrandName"},
{title:"NumPages"},
{title:"Position"}
]
});
}
});
I would make a little different, see how:
var theTable = $("#thetable").dataTable({
"aaData": [],
"aoColumns": [
{data:"AdId"},
{data:"BrandId"},
{data:"BrandName"},
{data:"NumPages"},
{data:"Position"}
]
}).DataTable();
$('#SortByCoverage').click(function () {
$.ajax({
url: '/Home/Question2',
type: 'GET',
dataType: 'json',
success: function (data) {
theTable.clear().draw();
table.rows.add(data)
.draw();
}
});

Categories