event handler are not working in asynchronous ajax call - javascript

i am filling up my dropdowns using this ajax call ..selectItems create select option tags in html using attribute_map
var $el = this.$el(model);
var rule_title = "Job Family: ";
var attribute_map = [];
var current_object = this;
$el.append(this.getRuleTitle(rule_title, model));
jQuery.ajax({
url : "<%= Rails.configuration.url_prefix %>/team/index/get_rule_attribute_values",
type : "GET",
data : { name : "jobFamily" },
dataType : "json",
success : function(data){
var attribute_array = data.value.rule_attribute_values;
attribute_array.sort(function(a,b){
if(a.display_name > b.display_name){
return 1;
}
if(a.display_name < b.display_name){
return -1;
}
return 0;
});
var index = 0;
var obj;
for (obj in attribute_array){
attribute_map[index] = [];
attribute_map[index][0] = attribute_array[index].display_name + " ( " + attribute_array[index].internal_name + " ) " ;
attribute_map[index][1] = attribute_array[index].internal_name;
index++;
}
current_object.selectItems($el,
attribute_map,
"jobFamily", model.jobFamily, {multiple : "multiple", "data-placeholder" : "Add Constraint..."}, "400px");
},
complete : function() {
console.log("completed");
},
error : function(jqXHR, textStatus,errorThrown){
var requestResponse = {
httpStatus: jqXHR.status,
error:jqXHR.statusText,
};
}
});
when i put async as false ..event handler works fine but in synchronous call , the just doesn't do anything
event handler looks like
$('.chosen-select jobFamily').on('change',function(evt, params){
console.log("completeddddddd");
var value = $('.chosen-select jobFamily').val();
console.log(value);
if (value == null) {
// Input is empty, so uncheck the box.
$('.jobFamily').prop("checked", false);
} else {
// Make sure the box is checked.
$('.jobFamily').prop("checked", true);
}
});
});
where '.chosen-select jobFamily' is class of select tag and '.jobFamily' is class of check box ... i have tried writing my jquery inside complete argument of ajax call , i tried writing my jquery inside
$('document).bind('ajaxComplete',function({
//above jquery
});
please help . i have spent more than 2 days on that . all code lies inside ready function.

Related

Failed to execute postMessage on window on Ajax

I've made a custom throttle for ajax requests.
Problem is I keep getting this error?
Uncaught TypeError: Failed to execute 'postMessage' on 'Window': 1 argument required, but only 0 present.
The line points to $.ajax({.
HTML:
<input class="image_title" />
<span class="the_title"></span>
JS:
$(function() {
var aj_count = 0;
var aj_flag = false;
var aj_flag2 = false;
var run_on = -1;
setInterval(function() {
aj_count++;
if (aj_flag === true) {
run_on = aj_count + 250;
aj_flag = false;
aj_flag2 = true;
}
if (run_on < aj_count && aj_flag2 === true) {
var $t = $(this);
var daid = $('.image_id').val();
aj_flag2 = false;
$.ajax({
type: "POST",
url: '/ajax/set_title.php',
data: {
'title' : $t,
'id' : daid
},
success: function(data) {
var data = JSON.parse(data);
$('.the_title').html( '<small>Title:</small> <strong>' + data.title + '</strong>' );
}
});
}
}, 1);
$('.image_title').on('input', function(e) {
aj_flag = true;
e.preventDefault();
return false;
});
$('.image_title').on('keydown', function(e) {
if (e.which == 13) {
e.preventDefault();
return false;
}
});
});
As you can see I have tried moving direct form vals into variables etc but I cannot get it to work anymore. When I replace the ajax section with a console.log it runs as expected. I've been looking around but I don't really understand what the error means still as ajax has an array passed to it.
Thank you for your time
The error is probably because of
var $t = $(this);
You're trying to send $t as the value of the title: parameter with
data: {
title: $t,
id: daid
},
But a jQuery object can't be serialized into a POST parameter.
You need to set $t to a proper title string. I don't know where that is in your application, but that should fix it.

Is it correct my ajax call and jQuery PHP for submit button only?

I'm using Kendo grid that has treeview with checkboxes. So, here I want to do POST using AJAX call to get the id of selected checkboxes. Is there any correction on this code? Because there is no function for submit button.
AJAX call for submit button
$("#primaryTextButton").kendoButton();
var button = $("#primaryTextButton").data("kendoButton");
button.bind("click", function(e) {
$.ajax({
type: "POST",
url: "getTest.php",
//data: { name: "John" }
data: function () {
return {
method: "getTemplate",
// employeeID: "<?php echo $_SESSION['employeeID'];?>",
// propertyID: "<?php echo $_SESSION['propertyID'];?>",
}
},
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
}
jQuery PHP
function getTemplate() {
global $ehorsObj;
$positionTemplateID = (isset($_POST['positionTemplateID']) ? $_POST['positionTemplateID'] : '');
$hrsPositionID = (isset($_POST['hrsPositionID']) ? $_POST['hrsPositionID'] : '');
$programID = (isset($_POST['programID']) ? $_POST['programID'] : '');
$propertyID = (isset($_POST['propertyID']) ? $_POST['propertyID'] : '');
$employeeID = (isset($_POST['employeeID']));
If they are using : If isset $_POST ,
I'm a little bit confused here. Is there any solution on this?
Demo Here
Your demo link has checkedNodeIds function. This function holds checked nodes in a multidimensional array like
nodes[i].moduleID
nodes[i].groupID
nodes[i].programID
So return this array from this function and pass it as ajax data. Then process it in your PHP back-end.
function checkedNodeIds(nodes, checkedNodes) {
for (var i = 0; i < nodes.length; i++) {
if (nodes[i].checked) {
//checkedNodes.push(nodes[i].moduleID);
// checkedNodes.push(nodes[i].groupID);
checkedNodes.push(nodes[i].programID);
}
if (nodes[i].hasChildren) {
checkedNodeIds(nodes[i].children.view(), checkedNodes);
}
}
}

How to wait for AJAX calls in an each loop to complete before moving on without ASYNC: FALSE

I currently have setup a AJAX to PHP set of functions that processes a number of items on a page. Basically the code inserts a series of tasks into the database, then inserts supplies into the database based on those newly created task ID's. However it works 90% of the time. Sometimes it seems as though the Task ID's are not created first which doesn't allow the supplies to use those ID's for inserting into the database. Is there a way to make sure that the task is inserted, then all supplies are inserted for that ID, then move onto the next one. At the end when all is complete I would like to redirect to a new page, again I put this in the last success call on the supplies portion, but it would redirect on the first loop. This process usually generates around 5 tasks, with 12 supplies per each task. I was reading about a $.when loop but could not get it to work. NOTE: after testing the ajax calls are submitting correctly, it was that one field on some of them was null, and the DB was having an issue. So the counter method below works.
$(document).on("click", "#submitTasks", function(e) {
e.preventDefault();
var tasks = $('#tasks').find('.box');
var project_id = $('#project_id').val();
tasks.each(function() {
var trs = $(this).find('.reqTables').find('.table').find('tbody').find('tr');
var task_definition_id = $(this).find('.task_definition_id').val();
var labor_type_id = $(this).find('.laborAmount').children('option:selected').val();
var task_status_id = 1;
var qty_labor = $(this).find('.laborQty').val();
var amount_labor = $(this).find('.laborTotal').val();
var amount_materials = $(this).find('.matTotal').val();
var amount_gst = $(this).find('.gstTotal').val();
amount_materials = +amount_materials + +amount_gst;
amount_materials = amount_materials.toFixed(2);
var active = 1;
//console.log(div)
var task = {
project_id : project_id,
task_definition_id : task_definition_id,
labor_type_id : labor_type_id,
task_status_id : task_status_id,
qty_labor : qty_labor,
amount_labor : amount_labor,
amount_materials : amount_materials,
active : active
};
saveTasks(task, trs, project_id);
});
});
function saveTasks(task, trs, project_id) {
$.ajax({
type : "POST",
url : "<?php echo base_url(); ?>" + "mgmt/project/saveTasks",
data : task,
dataType : "json",
cache : "false",
success : function(data) {
trs.each(function() {
var total = $(this).find('input[name="calculatedCost"]').val();
if (total != 'n/a') {
var task_id = data;
var supply_id = $(this).find('.suppliesPicker').children('option:selected').val();
var task_requirement_id = $(this).find('td:first-child').data('id');
var qty = $(this).find('input[name="calculatedQty"]').val();
var cost_per = $(this).find('.costPicker').val();
var delivery_cost = $(this).find('input[name="transport"]').val();
var notes = '';
var qty_actual = '';
var active = 1;
var taskSupply = {
task_id : task_id,
supply_id : supply_id,
task_requirement_id : task_requirement_id,
qty : qty,
cost_per : cost_per,
delivery_cost : delivery_cost,
total : total,
notes : notes,
qty_actual : qty_actual,
active : active
};
saveTaskSupplies(taskSupply);
console.log(taskSupply);
}
});
}
});
}
function saveTaskSupplies(taskSupply) {
$.ajax({
type : "POST",
url : "<?php echo base_url(); ?>" + "mgmt/project/saveTaskSupplies",
data : taskSupply,
dataType : "json",
cache : "false",
success : function(data) {
***** I WANT TO REDIRECT TO A NEW PAGE WHEN THE LAST ONE OF THESE COMPLETES ******
}
});
}
This code will wait for nested loop ajax function calls to finish their promises, then proceed..
var allPromises;
$(document).on("click", "#submitTasks", function(e) {
//...
var tasks = $('#tasks').find('.box');
allPromises = [];
tasks.each(function() {
//.. somehow getTask
var req = saveTasks(task, trs, project_id);
allPromises.push(req);
});
$.when.apply(null, allPromises).done(function(){
// Do your things here,
// All save functions have done.
});
});
function saveTasks(task, trs, project_id) {
return $.ajax({
// ,,, your codes
success : function(data) {
// ...
trs.each(function() {
// ... Somehow get taskSupply
var req = saveTaskSupplies(taskSupply);
allPromises.push(req);
}
}
});
}
function saveTaskSupplies(taskSupply) {
return $.ajax({
// ... bla bla bla
success : function(data) {
// Whatever..
}
});
}
Here is a direct solution using the code you provided. The basic concept is to increment a counter as supplies are processed. Once the counter reaches the total number of supplies, a procedure is run. See comments throughout.
var totalTaskSupplies = 0;
var processedTaskSupplies = 0;
$(document).on("click", "#submitTasks", function(e) {
e.preventDefault();
var tasks = $('#tasks').find('.box');
var project_id = $('#project_id').val();
tasks.each(function() {
var trs = $(this).find('.reqTables').find('.table').find('tbody').find('tr');
var task_definition_id = $(this).find('.task_definition_id').val();
var labor_type_id = $(this).find('.laborAmount').children('option:selected').val();
var task_status_id = 1;
var qty_labor = $(this).find('.laborQty').val();
var amount_labor = $(this).find('.laborTotal').val();
var amount_materials = $(this).find('.matTotal').val();
var amount_gst = $(this).find('.gstTotal').val();
// Add number of supplies for current task to total task supplies
totalTaskSupplies += trs.length;
amount_materials = +amount_materials + +amount_gst;
amount_materials = amount_materials.toFixed(2);
var active = 1;
//console.log(div)
var task = {
project_id : project_id,
task_definition_id : task_definition_id,
labor_type_id : labor_type_id,
task_status_id : task_status_id,
qty_labor : qty_labor,
amount_labor : amount_labor,
amount_materials : amount_materials,
active : active
};
saveTasks(task, trs, project_id);
});
});
function saveTasks(task, trs, project_id) {
$.ajax({
type : "POST",
url : "<?php echo base_url(); ?>" + "mgmt/project/saveTasks",
data : task,
dataType : "json",
cache : "false",
success : function(data) {
trs.each(function() {
var total = $(this).find('input[name="calculatedCost"]').val();
if (total != 'n/a') {
var task_id = data;
var supply_id = $(this).find('.suppliesPicker').children('option:selected').val();
var task_requirement_id = $(this).find('td:first-child').data('id');
var qty = $(this).find('input[name="calculatedQty"]').val();
var cost_per = $(this).find('.costPicker').val();
var delivery_cost = $(this).find('input[name="transport"]').val();
var notes = '';
var qty_actual = '';
var active = 1;
var taskSupply = {
task_id : task_id,
supply_id : supply_id,
task_requirement_id : task_requirement_id,
qty : qty,
cost_per : cost_per,
delivery_cost : delivery_cost,
total : total,
notes : notes,
qty_actual : qty_actual,
active : active
};
saveTaskSupplies(taskSupply);
console.log(taskSupply);
}
});
}
});
}
function saveTaskSupplies(taskSupply) {
$.ajax({
type : "POST",
url : "<?php echo base_url(); ?>" + "mgmt/project/saveTaskSupplies",
data : taskSupply,
dataType : "json",
cache : "false",
success : function(data) {
++processedTaskSupplies;
// All supplies have been processed
if (processedTaskSupplies == totalTaskSupplies) {
// Do something
}
}
});
}
Regarding the first question, by studying your code I couldn't see the reason of it. You only execute the saveTaskSupplies() when saveTasks() has executed successfully, so the task_id should already be created.
However, I would think of another possible problem from your backend, in your Ajax success function in saveTasks(), You assume the PHP script always execute successfully and return the task_id. Would it be possible that your PHP script has some problem and the task_id is not created in some instance?
For the second question, there are a few approaches, as #Seth suggest you can use jQuery.when, or you can create a global counter to keep track of whether the saveTaskSupplies() is the last one. Note that you should calculate the total length of trs before firing the Ajax request, otherwise, you may have a chance of having a not well-calculated total and redirecting before all tasks are done. If it is the last one it will redirect after successful Ajax call.
// create a global counter
var counter = 0,
trl = 0;
$(document).on("click", "#submitTasks", function(e) {
...
var trList = [];
tasks.each(function() {
// calculate the length of total task before actually firing the Ajax Request
var trs = $(this).find('.reqTables').find('.table').find('tbody').find('tr');
// keep a copy of the trs so the next each loop does not have to find it again
trList.push(trs);
trl += trs.length;
});
tasks.each(function() {
// get the trs of current iteration we have found in last loop
var trs = trList.shift();
...
saveTasks(task, trs, project_id);
});
});
function saveTasks(task, trs, project_id) {
$.ajax({
...
success : function(data) {
trs.each(function() {
...
saveTaskSupplies(taskSupply);
}
}
});
}
function saveTaskSupplies(taskSupply) {
$.ajax({
...
success : function(data) {
// check if the counter exceed the length of trs
if (++counter == trl) {
location.href = 'place you want to go';
}
}
});
}
On the other hand, for your task I would also suggest shifting the responsibility of data insertion to PHP backend, so all you need to do is to pass the task information and the task supplies at once to a single PHP script. This approach allows the use of Transaction to make sure all data insertion is success or otherwise all should fail.

Callback never called on Jquery.post();

I'm having some trouble using JQUERY Post function.
I have 2 functions that call JQUERY Post function.
Both of them is working fine, but the callback function is never called (handleLike).
When I call handleLike manually, it's works perfect.
(Even if handleLike has just an alert inside, the callback function is not called)
Could you please help me with this thing?
<script type="text/javascript">
$(document).ready(function() {
function handleLike(v_cb){
alert("Call back chamou!");
$('#erro').html(v_cb.mensagem);
if (v_cb.class == 'map'){
var elemento = $('#maplike');
}else{
var elemento = $('#commentlike'+v_cb.id);
}
if (!(elemento.hasClass('disabled'))){
elemento.addClass("disabled");
var likes = elemento.find('font').text();
likes++;
elemento.find('font').html(likes);
}
}
$('#maplike').click(function() {
//var map_id = $('#like').find('font').attr('value');
var id = $(this).attr("name");
if (!($(this).hasClass('disabled'))){
var JSONObject= {
"mensagem":"Testando Json",
"id":86,
"class":"map"
};
handleLike(JSONObject);
alert("Teste");
$.post(
'/cmap/maps/like',
{ id: id },
handleLike,
'json'
);
}
});
$('[id*="commentlike"]').click(function() {
//var map_id = $('#like').find('font').attr('value');
var id = $(this).attr("name");
if (!($(this).hasClass('disabled'))){
$.post(
'/cmap/comments/like',
{ id: id },
handleLike,
'json'
);
}
});
});
</script>
Diagnostic, not solution
Rationalizing and adding an error handler, you should get something like this :
$(document).ready(function() {
function handleLike(v_cb){
alert("Call back chamou!");
$('#erro').html(v_cb.mensagem);
var elemento = (v_cb.class && v_cb.class == 'map') ? $('#maplike') : $('#commentlike'+v_cb.id);
if (!elemento.hasClass('disabled')){
var f = elemento.addClass("disabled").find('font');
f.html(++Number(f.text()));
}
}
function ajaxError(jqXHR, textStatus, errorThrown) {
alert('$.post error: ' + textStatus + ' : ' + errorThrown);
};
$('#maplike').on('click', function() {
var $this = $(this);
if (!$this.hasClass('disabled')) {
$.post('/cmap/maps/like', { id: $this.attr("name") }, handleLike, 'json').fail(ajaxError);
}
});
$('[id*="commentlike"]').on('click', function() {
var $this = $(this);
if (!$this.hasClass('disabled')) {
$.post('/cmap/comments/like', { id: $this.attr("name") }, handleLike, 'json').fail(ajaxError);
}
});
});
untested
Barring mistakes, there's a good chance the error handler will inform you of what's going wrong.
I follow the Kevin B tip and use $ajax method.
It was a parseerror. Sorry.
The return of v_cb was not a json, it was a html. I correct my return, and everything was ok.

Refreshing Pagination in DataTables?

I'm having a strange issue that's only arising in my dataTable in select environments. I've written a function that allows the user to delete a row, then if it's the last row on that particular page, reload the Table and send the user to the 'new' last page.
However, on some servers, it's not working properly -- I think it has to do with the fact that with after using fnClearTable and fnDraw, the pagination of the table still holds the last 'empty' page.
Here's the function I'm working with now:
function fnDelete(elem) {
if (selected.length > 0) {
var c;
c = confirm("Are you sure you want to delete the selected Agency?");
if (c) {
var deleteURL = urlstr.substring(0, urlstr.lastIndexOf("/") + 1) + "delete.do";
deleteRecord(deleteURL, selected[0]);
if ($(".tableViewer tbody tr:visible").length === 1) {
oTable.fnClearTable();
oTable.fnDraw();
oTable.fnPageChange("last");
}}}}
In addition, here's my delet function.
function deleteRecord(deleteURL, iid){
var didDelete = false;
jQuery.ajax({
type: "POST",
url: deleteURL,
dataType:"html",
data:"recordID="+iid,
async : false,
success:function(response){
didDelete = true;
oTable.fnDraw(true);
selected = [];
selectedRecord = [];
enableButtons(selected);
},
error:function (xhr, ajaxOptions, thrownError){
<%-- is the message in a range we can handle? --%>
if ((xhr.status >=400) && (xhr.status < 500)) {
alert(xhr.responseText);
}
else {
alert('<spring:message arguments="" text="Internal Server Error" code="ajax.internal.server.error"/>');
}
}
});
return didDelete;
}
Again, this issue is only coming up on certain computers. Can anyone help?
Also, here's the configuration for my DataTable::
oTable = $('#${tableName}_grid').dataTable({
bDestroy: true,
bSort: true,
bFilter: true,
bJQueryUI: true,
bProcessing: true,
bAutoWidth: true,
bInfo: true,
bLengthChange: true,
iDisplayLength: ${sessionScope.displayLength},
sPaginationType: 'full_numbers',
bServerSide: true,
sAjaxSource: "<c:url value='${dataUrl}'/>",
aaSorting: [<c:forEach items="${sortInfo}" var="oneSort"> [${oneSort.columnIndex},'${oneSort.ascending ? "asc":"desc"}']</c:forEach>],
aoColumns: [
<c:forEach items="${columns}" var="curCol" varStatus="colLoop">
{sName: '${curCol.fieldName}', bSortable: ${curCol.sortable}, bSearchable: false, sTitle: "<c:out value='${curCol.title}'/>", sType: '${curCol.displayType}', bVisible:${curCol.visible}, vdbType:'${curCol.vdbType}', sClass:'${curCol.displayType}'}${colLoop.last ? '' : ','}
</c:forEach>
],
aoColumnDefs:[{sClass:"color_col", aTargets:['color']}],
fnRowCallback: function( nRow, aData, iDisplayIndex ) {
$('#${tableName}_grid tbody tr').each( function () {
if ($.inArray(aData[0], selected)!=-1) {
$(this).addClass('row_selected');
}
});
return nRow;
},
fnInfoCallback: function( oSettings, iStart, iEnd, iMax, iTotal, sPre ) {
if(myPos>=iStart && myPos<=iEnd){
//alert(myPos+" visible")
}else{
selected = [];
selected = [];
selectedRecord = [];
$('tr').removeClass('row_selected');
enableButtons(selected);
}
},
fnDrawCallback: function ( oSettings ) {
$('#${tableName}_grid tbody tr').each( function () {
var iPos = myPos = oTable.fnGetPosition( this );
if (iPos!=null) {
var aData = oTable.fnGetData( iPos );
if ($.inArray(aData[0], selected)!=-1) {
$(this).addClass('row_selected');
}
}
var htxt = '';
$(this).find('.color').filter(function(i,tdata){
htxt = '';
htxt = '#'+($(tdata).text());
return true;
}).css("background",htxt);
$(this).dblclick( function(){
var iPos = myPos = oTable.fnGetPosition(this);
var aData = oTable.fnGetData(iPos);
var iId = aData[0];
selected = [];
selectedRecord = [];
selected.push(iId);
selectedRecord.push(aData);
$('tr').removeClass('row_selected');
$(this).addClass('row_selected');
enableButtons(selected);
<%-- in case there is no edit button or its enablement is more complex,
// click the button instead of assuming it will call fnEdit.
// Do first() because jQuery is returning the same element multiple times.--%>
$(".${tableName}_bttns > span.edit-doubleclick:not(.disabld)").first().click();
});
$(this).click( function () {
var iPos = myPos = oTable.fnGetPosition(this);<%-- row index on_this_page --%>
var aData = oTable.fnGetData(iPos);
var iId = aData[0];
var is_in_array = $.inArray(iId, selected);
<%-- alert("iPos: " + iPos + "\nData: " + aData + "\niId: " + iId + "\nselected: " + selected + "\nis_in_array: " + is_in_array); --%>
selected = [];
selectedRecord = [];
if (is_in_array==-1) {
selected.push(iId);
selected.sort(function(a,b){return a-b});
selectedRecord.push(aData);
selectedRecord.sort(function(a,b){return a[0]-b[0]});
}
else {
selected = $.grep(selected, function(value) {
return value != iId;
});
selectedRecord = $.grep(selectedRecord, function(value) {
return value != aData;
});
}
if ( $(this).hasClass('row_selected') ) {
$(this).removeClass('row_selected');
}
else {
$('#${tableName}_grid tr').removeClass('row_selected');
$(this).addClass('row_selected');
}
enableButtons(selectedRecord);
});
});
} ,
"sDom": '<"H"lTfr>t<"F"ip>',
"oTableTools":{
"aButtons":[ {
"sExtends":"print",
"bShowAll": true,
"sInfo": printmsg,
"sButtonClass":"ui-icon fg-button ui-button edit-print DTTT_button_print",
"sButtonClassHover":"ui-icon fg-button ui-button edit-print DTTT_button_print"
} ] }
});
$('#${tableName}_grid_filter input').attr("maxlength", "255").attr("size", "35");
$('#${tableName}_grid').ready(function(){
$(".DTTT_containerc").remove();
BuildToolBarButtons();
var tt;
$(".DTTT_containerc").each(function(){
tt = $(this).find("#Print").attr("title");
$(this).find("#Print").remove();
$(this).find(".DTTT_container").remove();
}
);
$(".DTTT_container > button").attr("title",tt).css("border","1px solid #9597A3").removeClass("ui-state-default");
$(".DTTT_containerc").append($(".DTTT_container").removeAttr("style"));
});
});
Your datatable is configured to load data using ajax. This means that any action against the data happens asynchronously. Specifically, the fnDraw() function allows control to go to the statement where you change the page page before the new data is back from the server. You should move the logic that takes you to the last page to the fnDrawCallback. I believe that should resolve your issue.
Thought I'd write a response to help others to show how I fixed it.
#Gavin was correct in that it was in the wrong place -- I moved the function in question to the sucess callback in AJAX. However, to fix it fully, I had to 'premptively' read what page the deletion was happening on (using fn.PageChange plugin), subtract 1 (bc DataTables is zero-based) and send the user there.
Hope this helps anyone! #Gavin, thank you for your help and for leading me int he right direction!
you can keep on the same page after the table refreshed. you need to use the following snippet to keep your pagination same after refreshing datatable. just copy paste following js code on a separate file and hook it with your current page.
$.fn.dataTableExt.oApi.fnStandingRedraw = function(oSettings) {
if(oSettings.oFeatures.bServerSide === false){
var before = oSettings._iDisplayStart;
oSettings.oApi._fnReDraw(oSettings);
oSettings._iDisplayStart = before;
oSettings.oApi._fnCalculateEnd(oSettings);
}
oSettings.oApi._fnDraw(oSettings);
};
and now, you might be used the "fnDraw" to refresh the dataTable. So now, instead of that code. change it like this.
oTable1.fnStandingRedraw();
Now, your dataTable will keep the same page after refreshing it.

Categories

Resources