Reload DATATABLE inside AJAX success without refreshing page - javascript

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()

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

Storing JSON result from ajax request to a javascript variable for Easyautocomplete

I'm trying to implement the EasyAutoComplete plugin on a field based on the value filled in another field, using ajax requests.
I have a customerid field and when it's value changes, I want the productname field to show all products related to that customerid using the EasyAutoComplete plugin.
Here is what I have so far:
$('#customerid').on('change',function() {
var products2 = {
url: function(phrase) {
return "database/FetchCustomerProducts.php";
},
ajaxSettings: {
dataType: "json",
method: "POST",
data: {
dataType: "json"
}
},
preparePostData: function(data) {
data.phrase = $("#customerid").val();
return data;
},
getValue: "name",
list: {
onSelectItemEvent: function() {
var value = $("#productname").getSelectedItemData().id;
$("#productid").val(value).trigger("change");
},
match: {
enabled: true
}
}
};
$("#productname").easyAutocomplete(products2);
});
Contents of FetchCustomerProducts.php:
if(!empty($_POST["customerid"])){
$products = $app['database']->Select('products', 'customerid', $_POST['customerid']);
echo json_encode(['data' => $products]);
}
However it's not working. The code is based on the 'Ajax POST' example found on this page.
you can using element select category add is class "check_catogory"
after using event click element select get value is option, continue send id to ajax and in file php, you can get $_POST['id'] or $_GET['id'], select find database,after echo json_encode
$("#customerid").change(function(){
var id = $(this).val();
if(id!=""){
$.ajax({
url:"database/FetchCustomerProducts.php",
type:"POST",
data:{id:id},
dataType: "json",
cache:false,
success:function(result){
var options = {
data:result,
getValue: "name",
list: {
onSelectItemEvent: function() {
var value = $("#productname").getSelectedItemData().id;
$("#productid").val(value).trigger("change");
},
match: {
enabled: true
}
}
};
$("#productname").easyAutocomplete(options);
}
})
}
});

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().

Js variable does not update in ajax

I use jstree and want to reload it with new data but I cannot send it to new data.
var $driver = 0;
$(document).ready(function () {
$('#tree_folder').jstree({
'core': {
'check_callback': true,
"themes": {
"responsive": false
},
'data': {
type: "POST",
url: "Doc.aspx/Folder",
data: function () { return '{"driver":"' + $driver + '"}' },
contentType: "application/json"
}
}
});
});
$(document).on('click', '.tile', function () {
var $item = $(this);
var $driver = $item.attr('data-driver');
// alert($driver);
$('#tree_folder').jstree('refresh');
});
I got the new value when clicked, it send old default data every time. Above in alert function, it can give me the right value although json post send default one even data is written with function
function () { return '{"driver":"' + $driver + '"}' }
How can I get the new value from variable?
Remove var before $driver from .tile click function as you are created global previously,
Try this,
$(document).on('click', '.tile', function () {
var $item = $(this);
$driver = $item.attr('data-driver'); // remove var from this line
// alert($driver);
$('#tree_folder').jstree('refresh');
});
Also use cache:false in jstree like,
function getDriver() {
return '{"driver":"' + $driver+ '"}';
}
$(document).ready(function () {
$('#tree_folder').jstree({
'core': {
'check_callback': true,
"themes": {
"responsive": false
},
cache: false, // cache false
'data': {
type: "POST",
url: "Doc.aspx/Folder",
data: getDriver(), // get updated driver
contentType: "application/json"
}
}
});
});
Also take a look on change ajax options in jstree from server

How to display the searched data on the jgrid

this is related to my previous question about jqgrid. im doing now a search button that would search my inputed text from the server and display those data (if there is) in the jqgrid. Now, what i did is i create a global variable that stores the filters. Here's my javascript code for my searching and displaying:
filter = ''; //this is my global variable for storing filters
$('#btnsearchCode').click(function(){
var row_data = '';
var par = {
"SessionID": $.cookie("ID"),
"dataType": "data",
"filters":[{
"name":"code",
"comparison":"starts_with",
"value":$('#searchCode').val(),
}],
"recordLimit":50,
"recordOffset":0,
"rowDataAsObjects":false,
"queryRowCount":true,
"sort_descending_fields":"main_account_group_desc"
}
filter="[{'name':'main_account_group_code','comparison':'starts_with','value':$('#searchCode').val()}]";
$('#list1').setGridParam({
url:'json.php?path=' + encodeURI('data/view') + '&json=' + encodeURI(JSON.stringify(par)),
datatype: Settings.ajaxDataType,
});
$('#list1').trigger('reloadGrid');
$.ajax({
type: 'GET',
url: 'json.php?' + $.param({path:'data/view',json:JSON.stringify(par)}),
dataType: Settings.ajaxDataType,
success: function(data) {
if ('error' in data){
showMessage('ERROR: ' + data["error"]["msg"]);
}
else{
if ( (JSON.stringify(data.result.main.row)) <= 0){
alert('code not found');
}
else{
var root=[];
$.each(data['result']['main']['rowdata'], function(rowIndex, rowDataValue) {
var row = {};
$.each(rowDataValue, function(columnIndex, rowArrayValue) {
var fldName = data['result']['main']['metadata']['fields'][columnIndex].name;
row[fldName] = rowArrayValue;
});
root[rowIndex] = row;
row_data += JSON.stringify(root[rowIndex]) + '\r\n';
});
}
alert(row_data); //this alerts all the data that starts with the inputed text...
}
}
});
}
i observed that the code always enter this (i am planning this code to use with my other tables) so i put the filter here:
$.extend(jQuery.jgrid.defaults, {
datatype: 'json',
serializeGridData: function(postData) {
var jsonParams = {
'SessionID': $.cookie("ID"),
'dataType': 'data',
'filters': filter,
'recordLimit': postData.rows,
'recordOffset': postData.rows * (postData.page - 1),
'rowDataAsObjects': false,
'queryRowCount': true,
'sort_fields': postData.sidx
};
return 'json=' + JSON.stringify(jsonParams);
},
loadError: function(xhr, msg, e) {
showMessage('HTTP error: ' + JSON.stringify(msg) + '.');
},
});
now, my question is, why is it that that it displayed an error message "Server Error: Parameter 'dataType' is not specified"? I already declared dataType in my code like above but it seems that its not reading it. Is there anybody here who can help me in this on how to show the searched data on the grid?(a function is a good help)
I modified your code based on the information from both of your questions. As the result the code will be about the following:
var myGrid = $("#list1");
myGrid.jqGrid({
datatype: 'local',
url: 'json.php',
postData: {
path: 'data/view'
},
jsonReader: {
root: function(obj) {
var root = [], fields;
if (obj.hasOwnProperty('error')) {
alert(obj.error['class'] + ' error: ' + obj.error.msg);
} else {
fields = obj.result.main.metadata.fields;
$.each(obj.result.main.rowdata, function(rowIndex, rowDataValue) {
var row = {};
$.each(rowDataValue, function(columnIndex, rowArrayValue) {
row[fields[columnIndex].name] = rowArrayValue;
});
root.push(row);
});
}
return root;
},
page: "result.main.page",
total: "result.main.pageCount",
records: "result.main.rows",
repeatitems: false,
id: "0"
},
serializeGridData: function(postData) {
var filter = JSON.stringify([
{
name:'main_account_group_code',
comparison:'starts_with',
value:$('#searchCode').val()
}
]);
var jsonParams = {
SessionID: $.cookie("ID"),
dataType: 'data',
filters: filter,
recordLimit: postData.rows,
recordOffset: postData.rows * (postData.page - 1),
rowDataAsObjects: false,
queryRowCount: true,
sort_descending_fields:'main_account_group_desc',
sort_fields: postData.sidx
};
return $.extend({},postData,{json:JSON.stringify(jsonParams)});
},
loadError: function(xhr, msg, e) {
alert('HTTP error: ' + JSON.stringify(msg) + '.');
},
colNames:['Code', 'Description','Type'],
colModel:[
{name:'code'},
{name:'desc'},
{name:'type'}
],
rowNum:10,
viewrecords: true,
rowList:[10,50,100],
pager: '#tblDataPager1',
sortname: 'desc',
sortorder: 'desc',
loadonce:false,
height: 250,
caption: "Main Account"
});
$("#btnsearchCode").click(function() {
myGrid.setGridParam({datatype:'json',page:1}).trigger("reloadGrid");
});
You can see the code live here.
The code uses datatype:'local' at the beginning (at the 4th line), so you will have no requests to the server if the "Search" button is clicked. The serializeGridData the data from the postData parameter of serializeGridData will be combined with the postData parameter of jqGrid (the parameter "&path="+encodeURIComponent('data/view') will be appended). Additionally all standard jqGrid parameters will continue to be sent, and the new json parameter with your custom information will additionally be sent.
By the way, if you want rename some standard parameters used in the URL like the usage of recordLimit instead of rows you can use prmNames parameter in the form.
prmNames: { rows: "recordLimit" }

Categories

Resources