Ajax request don't start immediately - javascript

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.

Related

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

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!

JQuery Datatables not load immediately/disable autolaod

I am using JQuery Datatables 1.10.15 I would like to search first before loading the data because i have 300,000+ rows, maybe something like
if (table not loaded) {
(load the table)
}
else {
(Search)
}
or any other ways, please help me
this is my code:
var mytable = $('#myDatatable').DataTable({
"ajax": {
"url": '/Home/GetAllRecords',
"type": "POST",
"datatype": "json",
"data": (records)
},
"columns": [
{ "data": "id", "autoWidth": true },
{ "data": "name", "autoWidth": true }
]
});
$('#btnSearch').on("click", function () {
mytable.ajax.reload();
});

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

Get datatable current draw query string to send to server for export as report

I have a datatable drawing data from the server. i tried tabletools to export pdf and excel but it only exported what was on the first page of the datatable, it did not export including the other pages on the datatable pagination.
Therefore i want to the get the query string for the current draw so that i can add it to a link that points to another server request url which would generate report from there.
here is my datatable script:
table = $('#table').DataTable({
processing: true,
serverSide: true,
ajax: {
url: "http://xxxx/sales",
data: function ( d ) {
d.dateGroup = $(".btn.active").attr("data-ecvalue");
d.startDate = $("input[name=daterangepicker_start]").val();
d.endDate = $("input[name=daterangepicker_end]").val();
}},
"dom": 'T<"clear">lfrtip',
"tableTools": {
"aButtons": [
{
"sExtends": "copy",
"sButtonText": "Copy to clipboard"
},
{
"sExtends": "csv",
"sButtonText": "Save to CSV"
},
{
"sExtends": "xls",
"oSelectorOpts": {
page: 'current'
}
},
{
"sExtends": "download",
"sButtonText": "Download PDF",
"sUrl": "exportpdf"
}
]
},
type:"POST",
columns: [
{ "data": "date" },
{ "data": "order" },
{ "data": "totals" },
{ "data": "subtotals" }
]
});
I tried : var mydata = table.fnSettings();
alert(mydata );
but dont know how to do that.....
Am using datatables v1.10.
You're almost there with your code.
I was trying to do exactly what you explained. So, I managed this way:
$('#export-csv').on('click', function(){
var data = table.ajax.params();
var x = JSON.stringify(data, null, 4);
$(this).attr("href", this.href + "?" + $.param(data) + '&o=csv');
})

Categories

Resources