Datatables -Reinitializing datatables in a function - javascript

I'm still learning how to code js and datatables and I'm working on a crud using ajax. I have this code here:
load_data();
function load_data(is_suppliers)
{
var dataTable = $('#product_data').DataTable({
"processing":true,
"serverSide":true,
"order":[],
"ajax":{
url:"fetch.php",
type:"POST",
data:{is_suppliers:is_suppliers}
},
"columnDefs":[
{
"targets":[0,5,7,8],
"orderable":false,
},
],
});
}
This function is for column filtering and works with this code here:
$(document).on('change', '#supplier_filter', function(){
var supplier = $(this).val();
$('#product_data').DataTable().destroy();
if(supplier != '')
{
load_data(supplier);
}
else
{
load_data();
}
});
The problem is that the function initializes datatables:
var dataTable = $('#product_data').DataTable({});
and i have already initialized datatables for my crud operations so i cant use this code. How can use this function so it can work with my crud operation?

If you define the table's ajax datasource via a function, then you can determine the parameters to send along with your AJAX request at the time the call is made. Then, you can reload the datasource whenever you want, and the most current value of the filter will be send along in the payload.
Replace
"ajax":{
url:"fetch.php",
type:"POST",
data:{is_suppliers:is_suppliers}
},
With something like
ajax: function(data, callback, _settings) {
$.ajax({
type: 'POST',
url: 'fetch.php',
data: { is_suppliers: $('#supplier_filter').val() }
}).then(function(res) {
callback({ data: res });
});
},
Now, when the table first loads, it'll fetch the filter value from the filter control, and then send it along as part of the AJAX request.
Later, you can load the data again with
$('#product_data').DataTable().ajax.reload();
And at that time, it will look again at the filter widget, get the value, and send the new value along with a new AJAX request.

Related

how to make redraw datatables after ajax response

I have a problem here, first I create data tables after I select the user using select2, so the data is dynamic according to the selected user, then next to it there is an update data button, here serves to update the data from the API if there is the latest data, for the process the data update is no problem, but there is a problem in the data tables process where after the update process, the data tables don't want to be redrawn
$("#name").on("change",function(){
var cek_id = this.value;
$("#user_id").val(cek_id);
console.log(cek_id);
$('#getData').DataTable().clear().destroy();
var i = 1;
var VendorClient = $("#getData").DataTable({
order: [ 0, "asc" ],
processing: true,
serverSide: false,
ajax: "{{route('get-user-data')}}"+"/"+cek_id,
columns: [{
data: null,
render: function ( data, type, full, meta ) {
return meta.row+1;
} },
{
data: "fullname",
name: "fullname",
orderable:false
},
{
data: "date",
name: "date",
orderable:false
}
]
});
});
and here is the process when the data update is clicked
$("#get_data").on("click",function(){
var cek_id = $("#user_id").val();
var url = "{{route('get-update-data')}}"+"/"+cek_id,
$.ajax({
type: "get",
url: url,
dataType: "json",
success:function(data){
if(data.status=='success'){
$('#getData').data.reload();
}else{
$('#getData').data.reload();
}
}
});
});
I have tried various methods, including creating a globe variable for VendorClient, then after response ajax i'm adding this code VendorClient.ajax.reload(null, false); and get errorr (index):406 Uncaught (in promise) TypeError: Cannot read property 'ajax' of undefined
but it's not working, any ideas?
Try to redraw the table:
$('#getData').DataTable().clear().draw();
or
$('#getData').DataTable().columns.adjust().draw();
or
$('#getData').DataTable().columns.adjust().draw(false);

Call a php function with ajax variables using Silex framework (500 Internal Server Error)

I have two select lists in html and I would like to call a php function each time one value of both of these list changes. I already made the javascript file using ajax to get these values for each change. Now I would like to use these values to call my function each time there is a change as well. I'm using a POST request and a post route to get my data.
Here is my ajax.js file :
var year = $('#year option:selected').text();
var site = $('#site option:selected').val();
$.ajax({
type: 'POST',
url: 'previsionnel',
data: {
'year': year,
'site': site
},
success: function (data) {
$('#annualBudget').html(data);
},
error: function () {
alert('error');
}
});
$('#year, #site').change((function () {
$('#year').attr('selected');
$('#site').attr('selected');
var year = $('#year option:selected').text();
var site = $('#site option:selected').val();
$.ajax({
type: 'POST',
url: 'previsionnel',
data: {
'year': year,
'site': site
},
success: function (data) {
$('#annualBudget').html(data);
},
error: function () {
alert('error');
}
});
}));
Here is the routes.php file and the route where I call my function :
$app->post('/previsionnel', function (Request $request) use ($app) {
$year = $request->request->get('year');
$site = $request->request->get('site');
$app['dao.annualBudget']->getAnnualBudgetByYearAndSite($year, $site);
//return $app['twig']->render('previsionnel.html.twig', array('annualBudget' => $annualBudget));
});
For this code I have an 500 Internal Server Error for each POST requests made. After researches, I think I did an error somewhere or that's might be a server problem somehow. I want you to know that I'm not exactly sure it works this way so I might be wrong about how to get my data and then call my function.

Sending a JSON object to Django backend through AJAX call

I have the following code (jQuery) to create a json file:
$( ".save" ).on("click", function(){
var items=[];
$("tr.data").each(function() {
var item = {
item.Code : $(this).find('td:nth-child(1) span').html(),
itemQuantity : $(this).find('td:nth-child(4) span').html()
};
items.push(item);
});
});
Now this is my AJAX function:
(function() {
$.ajax({
url : "",
type: "POST",
data:{ //I need my items object, how do I send it to backend server (django)??
calltype:'save'},
dataType: "application/json", // datatype being sent
success : function(jsondata) {
//do something
},
error : function() {
//do something
}
});
}());
Now, my doubt is how do I send the 'item[]' object that I created to the backend? I do need to send both the item[] object and the variable 'calltype' which signals what made the AJAX call, as I have the same Django View (its the Controller equivalent for Django) in the backend being called by different AJAX functions.
How will my AJAX function look like?
Hey guys just got my answer right.
I used the following ajax function to get it right:
(function() {
$.ajax({
url : "",
type: "POST",
data:{ bill_details: items,
calltype: 'save',
'csrfmiddlewaretoken': csrf_token},
dataType: 'json',
// handle a successful response
success : function(jsondata) {
console.log(jsondata); // log the returned json to the console
alert(jsondata['name']);
},
// handle a non-successful response
error : function() {
console.log("Error"); // provide a bit more info about the error to the console
}
});
}());
So, this is sort of a self answer!!! :) Thanks a lot SO!!

How to define a function to modify data submitted to the server on Ajax request

I know that DataTables have the ajax.url() method for updating the data source URL, but I would like to know if there is a way I can change the function that is used to prepare the data to be POSTed on Ajax request. In the example below I would like to replace it with dataFunc.
The initialization part works fine.
function updateDataTable(dataFunc) {
// If DataTable initialised then update to correct function
if ($.fn.DataTable.isDataTable("#companyTable")) {
var companyTable = new $.fn.dataTable.Api("#companyTable");
companyTable.settings().ajax.data = dataFunc;
companyTable.ajax.reload();
} else {
$("#companyTable").DataTable({
bFilter: false,
processing: true,
serverSide: true,
ajax: {
url: "/api/GetCompanyRows",
type: "POST",
data: dataFunc
},
....
ajax can take a function where you can do all sorts of things, not the least of which is using localstorage. Check the documentation.
You can use ajax.data option to define a function that can be used to manipulate the data before it's sent to the server.
$('#companyTable').DataTable({
searching: false,
processing: true,
serverSide: true,
ajax: {
url: "/api/GetCompanyRows",
type: "POST",
data: function ( d ){
d.extra_search = $('#extra').val();
}
}
});
I found an alternative to Pro Hands solution, which allowed me to update the settings directly.
companyTable.settings()[0].ajax.data = dataFunc;
companyTable.ajax.reload();

How to change Ajax request type and data

I'm using jQuery DataTables and I have a table that is loading data via an Ajax request. The Ajax source is being set at initialization.
However, I would now like to change the request type to a POST and include a data object before I force an Ajax reload.
I am doing something like this, but it doesn't work:
dt.ajax.type = 'POST';
dt.ajax.data = {<some data here>};
dt.ajax.reload();
I am only able to change the Ajax source URL, but that doesn't need to change.
You can use ajax option to define a function to call $.ajax method as shown below:
$('#example').dataTable( {
"ajax": function (data, callback, settings) {
if(some_condition){
data.param1 = "A";
data.param2 = "B";
}
$.ajax( {
"dataType": "json",
"type": (some_condition) ? "GET" : "POST",
"url": "/json.php",
"data": data,
"success": callback
});
}
});
This function will be called on initialization and every time you call ajax.reload().

Categories

Resources