I'm using Angular Data Tables (0.5.2) with DataTables 1.10.12 to load a Data Table instance. In the UI I provide a DatePicker (start and end date) for the user to select in order to limit the data by a date range. When the user click a submit button, my plan is to send a Data Tables ajax request back to the server to perform a new query including the start and end dates.
I have the Data Tables ajax.reload() working in the code below, however, I cannot get the start and end date values added to the ajax form post. I've tried several different configurations but none have worked. Can anyone suggest a working solution to simply invoke an ajax request with custom parameters to the server so that it can reprocess the request and send back updated results to Data Tables? Thanks!
//HTML
<table datatable="" dt-instance="vm.dtInstance" dt-options="vm.dtOptions" dt-columns="vm.dtColumns" class="table table-striped table-bordered table-hover dataTable"></table>
//CONTROLLER
function dashboardDownloadsCtrl($scope, dataService, DTOptionsBuilder, DTColumnBuilder, DTInstanceFactory, DTRenderer) {
var vm = this;
vm.dtInstance = {};
vm.dtOptions = DTOptionsBuilder.newOptions()
.withDOM('<"html5buttons"B>lTfgitp')
.withOption('ajax', {
type: 'POST',
dataSrc: 'data',
url: dataService.dashboard.downloads.route
})
.withOption('fnPreDrawCallback', function () { console.log('loading..') })
.withOption('fnDrawCallback', function () { console.log('stop loading..') })
.withOption('processing', true)
.withOption('serverSide', true)
.withOption('responsive', true)
.withPaginationType('full_numbers');
vm.dtColumns = [
DTColumnBuilder.newColumn('RowNum').notVisible(),
DTColumnBuilder.newColumn('first_name').withTitle('First name'),
DTColumnBuilder.newColumn('last_name').withTitle('Last name')
];
}
// Directive submit button click
$('button.applyBtn').click(function () {
var $el = $(this);
var startDate = $('.daterangepicker_start_input input').val();
var endDate = $('.daterangepicker_end_input input').val();
//get reference to controller
var dtVm = scope.$parent.vm;
var dtInstance = dtVm.dtInstance.DataTable;
// add start and end date picker values to ajax data source and call reload
dtVm.dtOptions.ajax.data = function(d) {
d.datepicker_start_date = startDate;
d.datepicker_end_date = endDate;
};
var resetPaging = true;
dtInstance.ajax.reload(function(json){
console.log('callback');}, resetPaging);
});
I got it working by simply adding the data method initialization. Apparently, this has to be set before you update the field values in the Ajax reload callback.
.withOption('ajax', {
type: 'POST',
dataSrc: 'data',
url: dataService.dashboard.downloads.route,
data: function (d) {
d.datepicker_start_date = $('.daterangepicker_start_input input').val();
d.datepicker_end_date = $('.daterangepicker_end_input input').val();
}
})
Related
//ADDING NEW ITEM INTO THE ITEM TABLE
$(document).on('submit', '#product_form', function(event){
event.preventDefault();
btn_action="add_pricelvl"; //Set variable to call the add new item
var valdata = $(this).serialize(); //Array with field value
var tax = $('#item_tax').val(); //checkbox tax
var taxvalue = $('#item_taxvalue').val(); //inputbox tax
var tabledets = it_det //Read the detail table
.rows()
.data();
var arr1=[];
var i=0;
//Put the datatable rows in the array
for (i=0; i<tabledets.length; i++){
arr1[i]=tabledets.rows(i).data();
}
//call ajax function and send variable to php file.
$.ajax({
url:'item_action.php',
method:"POST",
data:{
btn_action:btn_action,
valdata:valdata,
tax:tax,
taxvalue:taxvalue,
arr1:arr1
},
success : function(data)
{
$('#product_form')[0].reset();
$('#productModal').modal('hide');
$('#alert_action').fadeIn().html('<div class="alert alert-success">'+data+'</div>');
$('#action').attr('disabled', false);
$('#item_data').DataTable().ajax.reload();
},
error : function () {
$('<div>').html('Found an error!');
}
})
});
That's my java code and I'm trying to call a php page and save all data in my DB. I got an error:
TypeError: 'insertCell' called on an object that does not implement interface HTMLTableRowElement.
That's happening when I insert data into the table "it_det"
Look the picture:
If I don't insert new rows into the table I don't get error!
What's wrong with that? Why I'm getting this error???
I found the solution changing the "processData" key to false
$.ajax({
processData: false, //The default value of ProcessData is true so changing in false I don't get any error.
url:'item_action.php',
method:"POST",
I have a data table that I am trying to append rows to when there is new data to display. I'm relatively inexperienced so I took the easy way out on this and wanted to write a script that checked the database for updates every second instead of listening for server-sent events. I tried to write an Ajax query that would get all the objects in the data table, and if their 6th value is false (which means they have not been loaded), then it would add a row to my data table with that information. My tables are in a Django webapp, and here's the code I have tried to implement:
<script type="text/javascript">
$(document).ready(function(){
var table = $('#example').DataTable();
setInterval(function(){
newrequests = $.ajax({
type: "GET",
url: "/main/newrequests/",
// I tried this and it didn't work
// success: function(data) {
// for(i = 0; i < data.length; i++){
// // check if the request has been loaded
// if(data[i][5] == 0)
// // if not, load and set to loaded
// table.row.add(data[i]).draw;
// data[i][5] == 1;
// }
// }
});
for(i=0; i<newrequests.length; i++){
if (newrequests[i][5] == 0){
table.row.add(newrequests[i]).draw();
newrequests[i][5] = 1;
}
}
}, 1000)
});
</script>
I have a view set up for /main/newrequests which simply all the objects in the database:
def newrequests(request):
return HttpResponse(Request.objects.all())
When I update the database, the data table does not refresh. Does anyone know what I am doing wrong? I feel like it might be how I am trying to use Ajax.
Datatable already has an option for that:
var table = $('#example').DataTable({
"ajax": '/main/newrequests'
});
setInterval(function () {
table.ajax.reload();
}, 30000 );
https://datatables.net/examples/data_sources/ajax.html
https://datatables.net/reference/api/ajax.reload()
In my project I'm using Parse.com as server and database, and DataTable plugin to create a table showing the data returned. There's no problem when I use a predefined json file, but when I try to construct a local json file using the data returned from Parse.com I get an error. It seems no matter what I do, the table creation process is run first and only afterwards the json object is created.
JSfiddle with the relevant code is here. Please note that due to the large amount of code I did not provide a working sample, but only the relevant part.
function getDataFromParse(){
console.log("test function run");
var loc_json={
"data":[]
};
//get data from parse
var parseTable = Parse.Object.extend("parseTable");
var tableObj = new parseTable();
var query = new Parse.Query(parseTable);
var count=0;
query.descending("createdAt");
query.find({
success: function(resultArr){
console.log("retreiving data from parse");
for(var i=0;i<resultArr.length;i++){
query.get(resultArr[i].id,{
success: function(tableObj){
var ret_phone = tableObj.get("phone");
var ret_first = tableObj.get("firstName");
var ret_last = tableObj.get("lastName");
var ret_status = tableObj.get("redemption_status");
var ret_vipCode = tableObj.get("vipCode");
loc_json.data.push([count,ret_first +" "+ret_last,ret_phone,tableObj.get("createdAt"),ret_vipCode]); //construction of local json
count++;
console.log("finished fetching data for "+ret_first+" "+ret_last);
},
error: function(object, error) {
console.log("could not do something "+error.message);
}
});
}
console.log("success function end");
},
error: function(error){
console.log(error.message);
}
});
console.log("trying to return json");
return loc_json;
}
var rows_selected = [];
console.log("table creation");
var table = $('#example').DataTable({
ajax: getDataFromParse(), // ajax: 'https://api.myjson.com/bins/4qr1g', THIS WORKS!!
columns: [
{},
{ data: 1},
{ data: 2 },
{ data: 3 }
],
'columnDefs': [{
'targets': 0,
'searchable':false,
'orderable':false,
'className': 'dt-body-center',
'render': function (data, type, full, meta){
return '<input type="checkbox">';
}
}],
'order': [1, 'asc'],
'rowCallback': function(row, data, dataIndex){
// Get row ID
$('input.editor-active', row).prop( 'checked', data[3] == 1 )
var rowId = data[0];
// If row ID is in the list of selected row IDs
if($.inArray(rowId, rows_selected) !== -1){
$(row).find('input[type="checkbox"]').prop('checked', true);
$(row).addClass('selected');
console.log("table trying to create itself");
}
}
});
SOLUTION
Remove ajax option from DataTables initialization options.
Call getDataFromParse() after initializing the DataTable
In the success handler for each query, replace this line:
loc_json.data.push([count, ret_first + " " + ret_last, ret_phone, tableObj.get("createdAt"), ret_vipCode]);
with the line below to add a new row to the table.
$('#example').DataTable()
.row.add([
count,
ret_first + " " + ret_last,
ret_phone,
tableObj.get("createdAt"),
ret_vipCode
])
.draw(false);
DEMO
See this jsFiddle for code and demonstration.
NOTES
The drawback of this solution is that a new row would be added once each query finishes successfully. Not sure if it is possible with Parse.com to handle event when all queries are completed.
Your example uses jQuery DataTables 1.9 but you're using option names and API from 1.10. You need to upgrade your jQuery DataTables library.
You're supplying data to jQuery DataTables using ajax option were in fact you should be using data option instead.
Remove code after // FOR TESTING ONLY as it was needed for demonstration only in jQuery DataTables - Row selection using checkboxes article and is not needed for production.
i have two forms on a page. 1st is shown and 2nd one is hidden.
1st form shows list of users and their emails in grid and pagination. when i select a multiple users from grid then a div shows up on the right side of the gird. which will be used to send email to selected user.
2nd form that shows up will input email subjects from users and then pass these whole data to django views.
i have user this ajax code to send whole data to the views function.
$("#_send").click(function(){
var frm = $('#messageform');
frm.submit(function () {
var selectedID = [];
$(':checkbox[name="selectedvalues[]"]:checked').each(function(){
selectedID.push($(this).data("email"));
});
$.ajax({
type: 'POST',
url: '/sendemail/',
processData: true,
data: {'frm':frm.serialize(),
'selectedID': selectedID},
success: function (data) {
alert(data);
},
error: function(data) {
alert("error");
}
});
return false;
});
});
and in django views i am catching like this;
def Send_Message(request):
checked_items = request.POST.getlist('selectedID[]')
Msg_Content = str(request.POST.get('content'))
frm = request.POST.get('frm')
print checked_items
print frm
print Msg_Content
it outputs like this;
abc#gmail.com,abc123#cogilent.comm
csrfmiddlewaretoken=dP7VkSQdWx0fXuX0kJC46arv6HFElvgz&subject=Hi+This+is+testing+message&content=ddddd
but i want these data seperately, message content and message subject.
When you serialize the data; you should be able to do request.POST.get('subject') etc
please pardon my noobness, but I'm new to working with Telerik controls. I have seen many examples of this but they haven't been able to solve my problem. I have a Kendo UI multiselect widget which contains some items and a button which, on clicking, would fill the multiselect widget partially with some items. These items are obtained as JSON from a controller method (ASP.NET MVC). So, the button click actually fires an ajax request and on successfully firing up, it calls a javascript function to fill the multiselect widget up. As of now, the ajax gets fired successfully and the data that I want is coming back successfully, just that the multiselect is not displaying the values.
My javascript/AJAX methods:
function addItems(items) {
var values = new Array();
for (var i = 0; i < items.length; i++) {
values[i] = items[i].Item.ID;
// gets values back correctly
console.log(values[i]);
}
// print values
$('#items').data("kendoMultiSelect").value(['"' + values + '"']);
};
// success
$(document).on("click", "#add-items-button", function () {
var myUrl = $('#MyURL').val();
$.ajax({
url: myUrl, // get URL from view
method: 'GET',
dataType: 'json',
success: function (data) {
addItems(data);
},
error: function (xhr, status, error) {
console.log(error);
}
});
});
My multiselect widget is a partial view so:
#using Kendo.Mvc.UI
#(Html.Kendo().MultiSelect()
.Name("items") // Name of the widget should be the same as the name of the property
.DataValueField("ID")
.DataTextField("Name")
.BindTo((System.Collections.IEnumerable)ViewData["items"])
.Placeholder("Add Items")
)
Am I missing something very obvious? Am I writing the data back in an incorrect format to the multiselect widget? Please help.
You need to add items to the data source of the multiselect.
$('#items').data("kendoMultiSelect").dataSource.add( { ID: 1, Name: "Name" });
Here is a live demo: http://jsbin.com/eseYidIt/1/edit
It might help to others
var multiSelect = $('#mymultiSelect').data('kendoMultiSelect');
var val = multiSelect.value().slice();
$.merge(val, "anil.singh#hotmail.com");
multiSelect.value(val);
multiSelect.refresh();
OR
$('#mymultiSelect').data("kendoMultiSelect").dataSource.add({Id:"EMP100XYZ",
EmailId: "ayz#gmail.com" });