Redraw datatables with search - ajax

I am using DataTables. I have added the below code when the page is loading and the table getting all data as expected.
var table = $('#expensesTable').DataTable({
responsive: true,
searchDelay: 500,
processing: true,
serverSide: true,
ajax: {
url: '/books/daybooks/datatable',
type: 'POST',
},
columns: [
{data: 'expense_id'},
{data: 'expense_date'},
{data: 'expense_description'},
{data: 'expense_amount'},
{data: 'vendor_name'},
],
});
Now, I have added a date range picker where it will search data in the server and response will be given back to query via Ajax.
$('#datepicker').on('apply.daterangepicker', function(ev, picker) {
var start = picker.startDate.format('YYYY-MM-DD');
var end = picker.endDate.format('YYYY-MM-DD');
jQuery.ajax({
type: "POST",
url: '/books/daybooks/datatable',
data: {start : start, end : end},
success: function(data)
{
console.log(data);
} // Success End
}); //AJAX End
});
Now i am getting all expected filter data as success, but now I need to redraw the table with newly got data after the filter of Ajax call.
if i use $('#expensesTable').DataTable().draw(); then it will do draw without filter,
So i can draw table with filter data?
Thanks in advance.

Instead of introducing a new ajax call (the jQuery ajax), you can re-use your existing DataTables ajax call when submitting your date range filter data.
To do this, you need to take the following steps:
(1) Update your DataTables ajax option:
ajax: {
url: '/books/daybooks/datatable',
type: 'POST',
data: function () {
return { "start": start, "end" end };
}
},
This data function allows you to dynamically assign values to your request. They will be added as standard URL-encoded form data, in the usual way for POST requests.
See here for more information. There are several different ways to use ajax.data. For example, if you were using serverSide processing (which you are not) then the above approach would not work correctly.
(2) To re-use your DataTables ajax call, you can use this:
table.ajax.reload();
See here for more information.
This replaces your jQuery ajax call:
var start;
var end;
$('#datepicker').on('apply.daterangepicker', function(ev, picker) {
start = picker.startDate.format('YYYY-MM-DD');
end = picker.endDate.format('YYYY-MM-DD');
table.ajax.reload();
});
When the table first loads (not using reload()), the filter values will be null.

Related

Using Datatables AltEditor requested unkown parameter

I'm having trouble with Datatable AltEditor when trying to update rows.
Btw, I'm using flask as back-end.
This is my setup:
First I'll show you what the datatable looks like
Html table:
<div id='contenidoBienvenida'>
<table class="dataTable table table-striped" id="example" style="width: 100%">
</table>
</div>
Flask Routes:
#app.route('/getProfesores') #This route sends the json data with all the teachers
def getProfesores():
if 'numEmpleado' in session:
try:
cur = mysql.connection.cursor()
cur.execute("SELECT * FROM usuarios")
r = [dict((cur.description[i][0], value) # IF NULO hacer algo
for i, value in enumerate(row)) for row in cur.fetchall()]
if (len(r) == 0):
return "No hay profesores"
return json.dumps({'data': r})
except Exception as e:
print(str(e))
return redirect(url_for('home'))
#This route receives the desired data to be edited, saves changes and returns new data as JSON
#app.route('/editar/profesor/', methods=['GET'])
def editarProfesor():
if 'numEmpleado' in session:
try:
numEmpleado = request.args.get('NumEmpleado')
nombre = request.args.get('nombre')
password = request.args.get('password')
correo = request.args.get('correo')
tipoCuenta = request.args.get('tipoCuenta')
perfilCompletado = request.args.get('perfilCompletado')
cur = mysql.connection.cursor()
query = "UPDATE usuarios SET NumEmpleado = %s, nombre = %s, password = %s, correo = %s, tipoCuenta = %s, perfilCompletado = %s WHERE NumEmpleado = %s"
cur.execute(query, (numEmpleado,nombre,password,correo,tipoCuenta,perfilCompletado,numEmpleado))
mysql.connection.commit() #Execute the update sql
cur.execute( #Now it grabs the edited row
"SELECT * FROM usuarios WHERE usuarios.NumEmpleado=%s" %
numEmpleado)
r = cur.fetchone()
cur.close()
return json.dumps({'data': r}) #sends the edited row as JSON -- SUCCESS
except Exception as e:
return redirect(url_for('home'))
profesoresDatatable.js:
$(document).ready(function() {
var columnDefs = [{
data: "NumEmpleado",
title: "Número Empleado",
},
{
data: "nombre",
title: "Nombre"
},
{
data: "password",
title: "Password"
},
{
data: "correo",
title: "Mail"
},
{
data: "tipoCuenta",
title: "Tipo Cuenta"
},
{
data: "perfilCompletado",
title: "¿perfilCompletado?"
}];
var myTable;
// local URLs are not allowed
var url_ws_mock_get = './getProfesores'; #Flask route which fill the datatable
var url_ws_mock_ok = './mock_svc_ok.json'; #not used
myTable = $('#example').DataTable({
"sPaginationType": "full_numbers",
destroy: true,
responsive: true,
ajax: {
url : url_ws_mock_get, #Flask route to obtain json data
// our data is an array of objects, in the root node instead of /data node, so we need 'dataSrc' parameter
dataSrc : 'data'
},
columns: columnDefs,
dom: 'Bfrtip', // Needs button container
select: 'single',
responsive: true,
altEditor: true, // Enable altEditor
buttons: [{
text: 'Agregar',
name: 'add' // do not change name
},
{
extend: 'selected', // Bind to Selected row
text: 'Editar',
name: 'edit' // do not change name
},
{
extend: 'selected', // Bind to Selected row
text: 'Borrar',
name: 'delete' // do not change name
},
{
text: 'Refrescar',
name: 'refresh' // do not change name
}],
onAddRow: function(datatable, rowdata, success, error) {
$.ajax({
// a tipycal url would be / with type='PUT'
url: url_ws_mock_ok,
type: 'GET',
data: rowdata,
success: success,
error: error
});
},
onDeleteRow: function(datatable, rowdata, success, error) {
$.ajax({
// a tipycal url would be /{id} with type='DELETE'
url: url_ws_mock_ok,
type: 'GET',
data: rowdata,
success: success,
error: error
});
},
onEditRow: function(datatable, rowdata, success, error) {
$.ajax({
// a tipycal url would be /{id} with type='POST'
url: './editar/profesor/', #flask route which save changes and returns edited row as JSON
type: 'GET',
data: rowdata,
success: success,
error: error
});
}
});
});
In the following example I will change the password for the user named Arturo Casanova, from '123' to 'password'
When I have finished editing and I click on save changes I get a warning about requested unknown parameters.
When I close the warning I get the success message
But the edited row is not inserted correctly
If I click on the Refrescar button(refresh button),it then will appear on the datatable correctly
This is the current JSON obtained by Flask Route'/getProfesores')
This is the JSON response after editing the row, the one that now should appear on the datatable
This are the scripts I'm using
<!--SCRIPTS-->
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
crossorigin="anonymous"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script type="text/javascript"
src="https://cdn.datatables.net/v/bs4/jszip-2.5.0/dt-1.10.18/b-1.5.6/b-colvis-1.5.6/b-flash-1.5.6/b-html5-1.5.6/r-2.2.2/sl-1.3.0/datatables.min.js"></script>
<script src="{{url_for('static', filename='js/dataTables.altEditor.free.js')}}"></script>
<script src="{{url_for('static', filename='js/profesoresDatatable.js')}}"></script>
Got it working
I changed the line 285 of dataTables.altEditor.free.js
that._editRowCallback(data,b,c,d,e); changed to that._editRowCallback(rowDataArray,b,c,d,e);
Complete section:
that.onEditRow(that,
rowDataArray,
function(data,b,c,d,e){ that._editRowCallback(rowDataArray,b,c,d,e); },
function(data){ that._errorCallback(data);
});
And now it doesn't show warnings and it refreshes as it should do
I know this was posted a while ago but I'll repsond as I had exactly the same problem, and also because I got in touch with the developers of the altEditor who responded below with a comment about the proposed fix.
The reason that the fix works is that it uses the JSON that the browser sent to the server, and it's valid JSON.
Without the proposed fix the editor uses the JSON returned by your server and I think you will find that this is where the problem is. As long as your server returns valid JSON with a key/value pair for each column in your table, it will work.
As an example, here's my table:
In the function called by onEditRow I create a string containing keys and values and then encode it to JSON and return it:
$row = '{"client_number": "1", "name": "Mark", "phone": "89797979", "link": "http://someserver.com"}';
echo json_encode($row);
With that code when I click the edit button on any row it will display the record from the table. When I click to close the edit dialog the row in the table will change to show that $row I returned. If you try that it should be enough to demonstrate that with valid JSON containing a value for each column, the editor works.
When I look in the browser to see what it received from the call to the server, it shows this:
And finally, here's the table after closing the edit dialog box. It shows that record I returned:
Obviously your server function will need to deal with the actual record clicked on and generate $row from that.
I know this is a bit old, but Mark's answer seems to be the correct one per the documentation on github.
AJAX Setup
The datatable accepts the following callback functions as arguments:
onAddRow(alteditor, rowdata, success, error)
onEditRow(alteditor, rowdata, success, error, originalrowdata)
onDeleteRow(alteditor, rowdata, success, error)
In the most common case, these function should call $.ajax as expected
by the webservice. The two functions success and error should be
passed as arguments to $.ajax.
Within the procedures onAddRow, onEditRow, onDeleteRow, you can access
datatable object using alteditor.s.dt.
Webservice must return the modified row in JSON format, because the
success() function expects this. Otherwise you have to write your own
success() callback (e.g. refreshing the whole table).
There needs to be a matching JSON response with the modified data to update the record natively

How to load kendo grid data with ajax call

How to load kendo grid data with ajax call using dataSource.data method. I have tried following but it is not working. $('#AAMaintenance').data('kendoGrid').dataSource.data(result);
function filterOnSubmit() {
var data = {};
data["ExaminerNo"] = $("#txtExaminerNo").val();
data["ExaminerName"] = $("#txtExaminerName").val();
$.ajax(
{
type: 'POST',
url: '#Url.Action("GetFilteredAAMaintenanceDetails", "AAMaintenance")',
contentType: "application/json",
dataType: 'json',
data: JSON.stringify({ aaMaintenanceFilter: data }),
success: function (result) {
$('#AAMaintenance').data('kendoGrid').dataSource.data(result);
$('#AAMaintenance').data('kendoGrid').refresh();
}
});
}
Assuming that the dataSource hasn't been setup for the Kendo grid control prior to the ajax call to retrieve the data, you should instantiate this before setting it as the datasource:
var ds = new kendo.data.DataSource({
data: result
});
$("#AAMaintenance").data("kendoGrid").setDataSource(ds);
A few notes aside from this, and based on Telerik documentation:
If the result returned from the server is a complex object (unknown currently), you may need to look into schema.model.
Ensure that the column declaration field attributes match the names assigned to the object attributes you wish to display, for example note in this example how the field: "name" column matches the name attribute being added to the dataSource.

Chained Select2 whith ajax json values

Have some problems to populate a Select2 with json data retrieved by ajax.
I check all samples from Select2-Github-AjaxData and other from StackOverFlow so always have same problem... the Json retrieved can't update next select2.
Some tries i use Jquery.Ajax to retrieve and assign:
function loadvariedad() {
var productIDVal= $("#frb_producto").val();
$.ajax ({
url: "http://www.fruitbull.info/api/json/es/v",
data: {idv: productIDVal, key:"123456"},
delay: 250,
dataType: 'json',
success: function(theResponse) {
$("#frb_variedad").select2({
data: theResponse.items
});
}
});
};
Other solution checked was the sample on Github form Ajax:
var productIDVal= $("#frb_producto").val();
$('#frb_variedad').select2({
ajax: {
url: 'http://www.fruitbull.info/api/json/es/v?key=123&idv='+productIDVal,
processResults: function (data) {
return {
results: data.items
};
}
}
});
Any idea or help to check?
My sample and tries on Fiddle
Solved by json origin data was formatted incorrectly

Use ajax to filtering data table in codeigniter

i'm using codeigniter to build my project. I want to make filter use select box with ajax, but i confused. when user choose values from select box, then i want the table just show data that contain select box values. Can anyone help me please...
<script>
function show_result()
{
if($('#selectbox').val()!='')
{
$.ajax({
type: "POST",
url:'<?php echo base_url()?>controller/controller_function',
data:'selectvalue='+$('#selectbox').val(),
cache: false,
beforeSend : function ()
{
$("#idAjaxLoader").css("display",'');
},
success: function (data) {
$("#idAjaxLoader").css("display",'none');
$('#table-div').html(data);
},
error: function(data){
//return false;
}
});
}
}
</script>
write query in controller's controller_function and then load view with table by your expected result

Updating a dropdown via knockout and ajax

I am trying to update a dropdown using knockout and data retrieved via an ajax call. The ajax call is triggered by clicking on a refresh link.
The dropdown is successfully populated when the page is first rendered. However, clicking refresh results in clearing the dropdown instead of repopulating with new data.
Html:
<select data-bind="options: pages, optionsText: 'Name', optionsCaption: 'Select a page...'"></select>
<a id="refreshpage">Refresh</a>
Script:
var initialData = "[{"Id":"231271443653720","Name":"Car2"},{"Id":"439319486078105","Name":"Electronics1.2"},{"Id":"115147185289433","Name":"Product"},{"Id":"145033098963549","Name":"Product2"}]";
var viewModel = {
pages : ko.mapping.fromJS(initialData)
};
ko.applyBindings(viewModel);
$('#refreshpage').click(function() {
$.ajax({
url: "#Url.Action("GetPageList", "FbWizard")",
type: "GET",
dataType: "json",
contentType: "application/json charset=utf-8",
processData: false,
success: function(data) {
if (data.Success) {
ko.mapping.updateFromJS(data.Data);
} else {
displayErrors(form, data.Errors);
}
}
});
});
Data from ajax call:
{
"Success": true,
"Data": "[{"Id":"231271443653720","Name":"Car2"},{"Id":"439319486078105","Name":"Electronics1.2"},{"Id":"115147185289433","Name":"Product"},{"Id":"145033098963549","Name":"Product2"}]"
}
What am I doing wrong?
The problem you have is that you are not telling the mapping plugin what to target. How is it suppose to know that the data you are passing is supposed to be mapped to the pages collection.
Here is a simplified version of your code that tells the mapping what target.
BTW The initialData and ajax result were the same so you wouldn't have noticed a change if it had worked.
http://jsfiddle.net/madcapnmckay/gkLgZ/
var initialData = [{"Id":"231271443653720","Name":"Car2"},{"Id":"439319486078105","Name":"Electronics1.2"},{"Id":"115147185289433","Name":"Product"},{"Id":"145033098963549","Name":"Product2"}];
var json = [{"Id":"231271443653720","Name":"Car2"},{"Id":"439319486078105","Name":"Electronics1.2"},{"Id":"115147185289433","Name":"Product"}];
var viewModel = function() {
var self = this;
this.pages = ko.mapping.fromJS(initialData);
this.refresh = function () {
ko.mapping.fromJS(json, self.pages);
};
};
ko.applyBindings(new viewModel());
I removed the jquery click binding. Is there any reason you need to use a jquery click bind instead of a Knockout binding? It's not recommended to mix the two if possible, it dilutes the separation of concerns that KO is so good at enforcing.
Hope this helps.

Resources