Datatables: dynamic page load in modal, based on row values - javascript

I am trying something really complex here, and I have not worked out a way to implement a solution yet. The part I work on looks like this:
1. simple page A that dynamically loads datatable from db.Last col is a button.
2. an html page B that loads different things according to 2 values stored at at local storage. these are available in the aforementioned table.
Now the part I cannot figure out:
3. Into the simple page A, there is a modal div. I want to load the B page into this modal on button click, and load different data, according to the values stored at local storage.
Here is my code so far:
function getadminprojects(){ //function that dynamically loads datatable
$.ajax({
url: "http://....../CustomServices/DBDistApps",
type: "GET",
dataType: 'json',
async: false,
success: function(data) {
$('#projectsdt').show();
projectsTable = $('#projectsdt').DataTable({
"pageLength": 10,
"data": data,
"scrollX": true,
"order": [[ 4, "desc" ]],
//"aaSorting": [],
"columns": [
{ "data": "code" },
{ "data": "descr" },
{ "data": "manager" },
{ "data": "customer" },
{ "data": "link_date" },
{ "data": "delink_date"},
{ "data": "type"},
{
"data": null,
"defaultContent": "<button class='btn btn-warning' onclick='openmodal2();'>button1</button>"
},
{
"data": null,
"defaultContent": "<button class='btn btn-success' onclick='localStorage.setItem('username',"+row.customer+");localStorage.setItem('projectid',"+row.code+"); projectpopmodal(); '>button2</button>"
},
] ,
});
$('#projectsdt thead').on('click', 'tr', function () {
var data2 = table.row( this ).data();
alert( 'You clicked on '+data2[0]+'\'s row' );
} );
$('#projectsdt').show();
$('#projectsdt').draw();
}
});
}
function projectpopmodal(){
$('#showfreakinmap').load('newprojects.html');
$('#fsModal').modal('show');
}//function to load page B into modal of page A
Thank you in advance!

Related

how to save table state even after changing table pages

I have a dataTable that displays data from a database. I'ts displayed in a bootstrap modal and there is an option in each row to delete the row.
Here's the jquery that gets the data from the database:
function cart_contents() {
$.ajax({
url: "cartContents.php",
type: "POST",
dataType: "JSON",
success: function(data){
var table = $('#cart-content').dataTable();
table.fnDestroy();
table.dataTable({
"aaData": data,
"scrollX": false,
"lengthChange": false,
"ordering": false,
"pageLength": 6,
"language": {
"info": "Number of items: _TOTAL_"
},
"searching": false,
"aoColumns": [
{"sTitle": "Product", "mData": "product"},
{"sTitle": "Price", "mData": "price"},
{"sTitle": "Qty.", "mData": "quantity"},
{
"sTitle": "Edit", "mData": "id", "render": function (mData, type, row, meta) {
return '<button class="btn btn-xs btn-success" onclick="sample(' + mData + ')">Edit</button>';
}
},
{
"mData": "id", "render": function (mData, type, row, meta){
return "<span style='cursor: pointer' class='close' onclick='remove_product(this," + mData + ")'>x</span>";
}
}
]
})
}
}
Here's the remove_product:
function remove_product(these, id){
var i = these.parentNode.parentNode.rowIndex;
document.getElementById("cart-content").deleteRow(i);
$.ajax({
type: "POST",
url: "remove_product.php",
data: {product_id: id},
success: function(data){
alert(data);
}
})
}
Now, the data may or may not exceed a single page on the table since it is set to display 6 rows. Therefore, there is a chance that there may be pagination. Whenever the 'x' is clicked to remove the row, it removes it on the page, and successfully deletes it in the database.
However, when I scroll to the next page of the table and go back previously, the row that was deleted comes back. How would I go about deleting it permanently, since it no longer exists in the database? I need to do this without reloading the modal.

Trying to access dataTable variable outside ajax is giving undefined

I have a jquery autocomplete that once a value is selected it loads a datatable with checkbox from an ajax call. Then while submitting the form I need to access the datatable variable to iterate each row to get the selected ones, but the datatable variable appears as undefined.
I'm doing the same as in this example, only difference is the data is coming from an Ajax request.
Can you please help me understand why is that happening?
$(document).ready(function() {
var campId;
var t_OmnitureCode;
// Campaign input autocomplete
$("#campaign").autocomplete({
source: function(request, response) {
$.ajax({
url: "promotion",
type: "GET",
data: {
term: request.term,
action: "searchCampaign"
},
dataType: "json",
success: function(data) {
if (!data.length) {
var result = [{
label: "no match found",
value: "-1"
}];
response(result);
} else {
response($.map(data, function(item) {
return {
label: item.name,
value: item.campaignId
}
}));
}
}
});
},
select: function(event, ui) {
event.preventDefault();
campId = ui.item.value;
if (campId != "-1") {
this.value = ui.item.label;
// This will apply datatables getting the content from an Ajax call
t_OmnitureCode = applyDataTableOmnitureCode(campId);
}
},
focus: function(event, ui) {
event.preventDefault();
this.value = ui.item.label;
}
});
// Handling form submission
$("#frm_promotion").on("submit", function(e) {
var form = this;
// Variable for datatable "t_OmnitureCode" is undefined below
var rows_selected = t_OmnitureCode.column(0).checkboxes.selected();
EDIT:
Just realized that even while assigning the variable (t_OmnitureCode = applyDataTableOmnitureCode(campId);) it is undefined, not sure why.
Here is the applyDataTableOmnitureCode code:
function applyDataTableOmnitureCode(campId) {
$("#tbl_omnitureCode").DataTable({
destroy: true,
scrollX: true,
fixedColumns: {
leftColumns: 1
},
"ajax": {
"url": "promotion",
"type": "GET",
"data": {
action: "searchOmnitureCodesByCampaignId",
campaignId: campId
},
"dataSrc": ""
},
"columns": [
{ "data": "key" },
{ "data": "omnitureCode" },
{ "data": "urlAppName" },
{ "data": "language" },
{ "data": "channel" },
{ "data": "createDateTime", "defaultContent": "" },
{ "data": "updateDateTime", "defaultContent": "" }
],
"columnDefs": [
{ "targets": 0, "checkboxes": { "selectRow": true } }
],
"select": {
"style": "multi"
},
"order": [[1, "asc"]],
"fnInitComplete": function() {
$("#omnitureCodeSection").show();
}
});
};
You may need to grab your DataTables object into a variable before using that:
var t_OmnitureCode = $("#tbl_omnitureCode").DataTable();
var rows_selected = t_OmnitureCode.column(0).checkboxes.selected();
And, by the way, your method of populating DataTable with external ajax-call is suboptimal. There's an ajax option for that purpose where you can specify all the necessary parameters and get better integration with DataTables API and better performance (as you don't really need to destroy and create your DataTable upon each refresh).
You would simply need to trigger .ajax.reload() whenever you need to refresh your table data.
It's a matter of scope : You declare the variable table inside $(document).ready function.
You may want to put it outside in the global scope :
var table;
$(document).ready(function() {
table = $('#example').DataTable({
...
});

Ajax request don't start immediately

How can i stop this from autoplaying, I have a search button and I want to search first before getting the data, any approach is okay to me, whether it's AJAX side or Javascript side, please help.
Javascript
var table = $('#SARDatatable').DataTable({
"processing": true,
dom: "<'row'<'col-sm-6'l><'col-sm-6'f>>" +
"<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-2'i><'col-sm-5'B><'col-sm-5'p>>",
buttons: [
'copyHtml5',
'excelHtml5',
'csvHtml5',
'pdfHtml5',
'print'
],
"ajax": {
"url": '/Home/GetAllSAR',
"type": "POST",
"datatype": "json",
"data": function (d) {
d.searchParameters = {};
d.searchParameters.sarcode = $('#txtSAR').val();
d.searchParameters.stype = $('#txtSType').val();
}
},
"columns": [
{ "data": "sarcode", "autoWidth": true },
{ "data": "stype", "autoWidth": true },
{ "data": "amount", "autoWidth": true },
{ "data": "filterno", "autoWidth": true }
]
});
$('#btnSearch').on("click", function () {
table.ajax.reload();
});
If I understand you correctly, you would like to only initialize the table after a button has been clicked, so that the AJAX request to get the data will not be issued before clicking the button.
If this is the case, then I would suggest the following:
Have a button that inits the table:
HTML
<button id='initTable'>Init Table</button>
JavaScript
var table;
$('#initTable').on('click', function() {
table = $('#SARDatatable').DataTable({ // code to init the DataTable });
});
Have the 'reload' button
HTML
<button id='btnSearch'>Reload</button>
JavaScript
$('#btnSearch').on("click", function () {
table.ajax.reload();
});
After you init the table, you can hide the "Init Table" button, so that there will be only one button at a time.
Hope this helps.

Datatables - dynamic columns

I understand that this question has been asked before, but my variation does not match the other answers.
I have a json data source in this form :
{
"columns":[
{"title":"Store Number","data":"StoreNbr"},
{"title":"Store Name","data":"StoreName"},
{"title":"2016-01-01","data":"2016-01-01"},
{"title":"2016-01-02","data":"2016-01-02"}
],
"data":[
{"2016-01-01":"51","StoreNbr":"1","StoreName":"Store 1","2016-01-02":"52"}
]
}
I am loading the data like this :
$("#datatable").DataTable({
"ajax": {
"url": "http://myjsonurl-that-produces-above-response",
"dataSrc": "data"
},
"columns": [
{"title":"Store Number","data":"StoreNbr"},
{"title":"Store Name","data":"StoreName"},
{"title":"2016-01-01","data":"2016-01-01"},
{"title":"2016-01-02","data":"2016-01-02"},
],
dom: "Bfrtip",
"bProcessing": true,
"bServerSide" : true
});
The above works flawlessly. What I need, is to load the columns dynamically, like this :
"columns": $.getJSON($('#datatable').DataTable().ajax.url(),
function(json){
return (JSON.stringify(json.columns));
});
All I get is a aDataSource error.
If I run the .getJSON thing anywhere else in the code I get the expected response, the one I need. Any ideas?
I would like to make this to work as it is preferably as my datasource keeps changing based on filters I apply that affect the json source, dataset etc.
Update :
The way the table is initialized :
<script type="text/javascript">
TableManageButtons.init();
TableManageButtons = function () {"use strict"; return { init: function () { handleDataTableButtons() } }}();
var handleDataTableButtons = function () {
"use strict";
0 !== $("#datatable-buttons").length && $("#datatable-buttons").DataTable({
"ajax": {
"url": "http://myjsonurl.php",
.......
Try to get the columns first and then proceed with datatables initialization:
$.getJSON('url/for/colums', function(columnsData) {
$("#datatable").DataTable({
...
"columns": columnsData
});
});
EDIT
If I understand correctly, you want to do this:
$("#datatable").DataTable({
"ajax": {
"url": "http://myjsonurl-that-produces-above-response",
"dataSrc": "data"
},
"columns": getColumns(), //Execute $.getJSON --> asynchronous (the code continous executing without the columns result)
dom: "Bfrtip",
"bProcessing": true,
"bServerSide" : true
});
In this way, when you call getColumns() the execution is asynchronous, so the columns are going to be undefined.
That's why you have to call the DataTable initializer in the getJSON callback function.
Another way might be to get the columns in a not asynchronous function setting async: false (Check this question)
You can form a custom js function to put your headers in place once you get the response from server. Have a look into below code:
JSON response from server:
{
"columns": [
[ "Name" ],
[ "Position" ],
[ "Office" ],
[ "Extn." ],
[ "Start date" ],
[ "Salary" ]
],
"data": [
[
"Tiger Nixon",
"System Architect",
"Edinburgh",
"5421",
"2011/04/25",
"$320,800"
],....
}
And js method to process it to put headers on place:
$( document ).ready( function( $ ) {
$.ajax({
"url": 'arrays_short.txt',
"success": function(json) {
var tableHeaders;
$.each(json.columns, function(i, val){
tableHeaders += "<th>" + val + "</th>";
});
$("#tableDiv").empty();
$("#tableDiv").append('<table id="displayTable" class="display" cellspacing="0" width="100%"><thead><tr>' + tableHeaders + '</tr></thead></table>');
//$("#tableDiv").find("table thead tr").append(tableHeaders);
$('#displayTable').dataTable(json);
},
"dataType": "json"
});
});
Check this url for more clarification.
Hope this helps!!

jquery data table and sorting columns

I'm using jquery data table to display large amounts of data inside grid. I implemented server side pagination but I'm struggling with sorting data server side.
Below is my datatable initialization, answer with query for sorting is not the subject here, I just need a way to pass information of which column is clicked to the controller, the one upon I will do the sorting.
('#myTable').dataTable({
"processing": true,
"serverSide": true,
"info": false,
"pageLength": 10,
"lengthChange": false,
"stateSave": false,
"bPaginate": true,
"bFilter": false,
"sPaginationType": "full_numbers",
"info": "Page _PAGE_ from _PAGES_",
"infoEmpty": "No data",
"oPaginate": {
"sFirst": "First",
"sPrevious": "Previous",
"sNext": "Next",
"sLast": "Last"
},
"ajax": {
"url": "#string.Format("{0}://{1}{2}", Request.Url.Scheme, Request.Url.Authority, Url.Content("~"))/MyController/GetData",
"type": "GET",
"data": function (d) {
.....
},
},
preDrawCallback: function (settings) {
...
},
drawCallback: function (settings) {
...
},
"columns": [
{ "data": "Id" },
{ "data": "FirstName" },
{ "data": "LastName" },
{ "data": "Age" }
],
"columnDefs": [
{
targets: [0],
orderable: false
},
{
render: function (data, type, row) {
...
}
],
"order": [[0, "desc"]]
});
public ActionResult GetData(){
var sortColumn = ...
...
}
You can bind the 'order' event like this:
$('#myTable').on( 'order.dt', function () {
var order = table.order();
var column_selected = order[0][0];
var order_way= order[0][1];
doStuff(column_selected ,order_way);
});
See it in plugin reference
By specifying "serverSide": true,, datatables will by default add information to the request which you need to use in your server-side code. If you look in the Firebug Network panel, you will be able to see the request with the querystring parameters. See here for the full list of parameters. Note that the link is to the v1.9 documentation, because that's what it looks like you're using.
So for sorting, you'd be interested in iSortCol_0 and sSortDir_0 which relate to the clicked column and the sort direction respectively.
In your controller method, you would access the parameters like this:
var sortColumnIndex = Convert.ToInt32(Request["iSortCol_0"]);
var sortColumnDir = Request["sSortDir_0"];
You then need to incorporate this, and the other parameters into your query.
Here is an article on using server-side datatables with MVC

Categories

Resources