I was wandering if its possible to pass in a different parameter to a controller using Ajax.reload() in datatables.
thanks to another topic on stackoverflow, I was able to pass in parameter from my variable in to url.Action on creating the table new { cyfy = "_Switch" })".replace("_Switch",Switch)
Then on button click i change the state of the variable ( to 0 or 1 ) and call Ajax.reload() on my table.
The issues is that controller receives the same parameter value on each reload. It seems that this part is not run with the reload:
"ajax": {
"url": "#Url.Action("GetProjects", "mytool",new { cyfy = "_Switch" })".replace("_Switch",Switch),
"type": "get",
"datatype": "json"
},
I was wandering if there is a way to pass in different parameter value on datatables ajax.realod ?
Below bigger part of the code:
$("#toggle").change(function () {
if ($('#toggle').is(':checked') == true) {
Switch = 1
}
else {
Switch = 0
}
/////////////////
var oTable = $('#myDatatable').DataTable({
"bPaginate": false,
dom: 'Bifrtp',
"ajax": {
"url": "#Url.Action("GetProjects", "mytool",new { cyfy = "_Switch" })".replace("_Switch",Switch),
"type": "get",
"datatype": "json"
},
Solved.
The issue was that Ajax was adding timestamp to the request on the reload.
to solve this I have added cache : true, option while creating a table.
and then I am reloading the table using ajax.url
var testURL = CreateUrl("mytool/GetProjects?cyfy=") + Switch;
$('#myDatatable').DataTable().ajax.url(testURL).load();
Related
I'm using the Javascript Datatable with server side searching.
So:
var table = $('#myTable').DataTable({
responsive: true,
serverSide: true,
ajax: {
url: myUrl,
dataSrc: ''
},
fnServerData: function (sSource, aoData, fnCallback, oSettings)
{
oSettings.jqXHR = $.ajax({
url: myUrl,
success: function (json, status, xhr) {
//Do stuff
}
});
}
});
I build the url dynamically using options set on my form.
I would like a button on my form so I can manually trigger the fnServerData function. At the moment I have to type into the included search box.
e.g. <button ng-click="model.search()">Search</button>
Is this possible?
Thanks
Here is the code that I used for refresh the DataTable
var table = $("#gridId").dataTable();
//if you want to add extra parameters in the query
/*table.fnSettings().ajax.data = function (d) {
$.extend(d, jsonPostData);
};
*/
table.fnDraw(false);
I've found a solution:
var oTable = $('#myTable').dataTable();
oTable.fnFilter('');
With the latest DataTable, you need to use following in order to trigger server side call:
table.draw();
I'm trying add data to DB and show these data in same page using ajax and jQuery datatable without reloading or refreshing page. My code is saving and retrieving data to/from database. But updated data list is not showing in datatable without typing in search box or clicking on table header. Facing same problem while loading page.
Here is my code
//show data page onload
$(document).ready(function() {
catTable = $('#cat_table').DataTable( {
columns: [
{ title: "Name" },
{ title: "Level" },
{ title: "Create Date" },
{ title: "Status" }
]
});
get_cat_list();
});
//save new entry and refresh data list
$.ajax({
url: 'category_save.php',
type: 'POST',
data:{name: name,level: level},
success: function (data) {
get_cat_list();
},
error: function (data) {
alert(data);
}
});
//function to retrieve data from database
function get_cat_list() {
catTable.clear();
$.ajax({
url: 'get_category_list.php',
dataType: 'JSON',
success: function (data) {
$.each(data, function() {
catTable.row.add([
this.name,
this.level,
this.create_date,
this.status
] );
});
}
});
}
The solution is here - for DataTable server side data source enabled
.draw() will cause your entire datatable to reload, say you set it to show 100 rows, after called .row().add().draw() > datatable will reload the 100 rows again from the server
I wasted an hour trying to find any solution for this very old question, even on DataTable official support there is no good solution suggested ...
My solution is
1- call .row().add()
2- do not call .draw()
3- your row must have an Id identifier to use it as a selector (check the rowId setting of the datatable)
4- after calling .row().add(), the datatable will have the row added to it's local data
5- we need to get this row from datatable object and transform it to HTML using the builtin method .node()
6- we gonna prepend the result HTML to the table :)
All that can be done in two lines of code
var rowData = someRowCreatedByAnAjaxRequest;
myDataTableObject.row.add(rowData);
$("#myTable-dt tbody").prepend(myDataTableObject.row(`tr#${rowData.Id}`).node().outerHTML)
Thanks ☺
From the documentation,
This method will add the data to the table internally, but does not
visually update the tables display to account for this new data.
In order to have the table's display updated, use the draw() method, which can be called simply as a chained method of the row.add() method's returned object.
So you success method would look something like this,
$.each(data, function() {
catTable.row.add([
this.name,
this.level,
this.create_date,
this.status
]).draw();
});
I have a DataTables (datatables.net) table setup which have a custom column where I have icons for different kind of actions.
One of these actions is deletion and I don't want to reload the data into the table so I was wondering if there was any function built-in for removal of datatable rows locally (so my script deletes the actual post on the server and then I can remove the same row in my datatable).
After some research I've found "fnDeleteRow" but I don't know how to use it. In my script I have an ajax call and on the success event I want to delete the row but I have trouble identifying what row that had the link was clicked. This below is where I am at the moment:
function Delete(id) {
$.ajax({
url: "ajax/ajax.php",
type: "POST",
data: {
action: "delete",
id: id
},
success: function(response){
oTable = $('#table').DataTable();
var row = oTable.closest('tr');
var nRow = row[0];
oTable.DataTable().fnDeleteRow(nRow);
},
error: function (response) {
alert("Something went wrong.");
console.log(response);
},
});
};
This prints the following in the console:
TypeError: oTable.closest is not a function
I'm pretty new to jQuery and don't know how to implement this to my case. Do anyone of you have any idea? I'm guessing that even if my script within the success event had the right syntax, it won't have a clue what row had the button/link that was clicked at the first place. How do I ensure it does?
EDIT:
This is how my datatable is initiated, in case it is confusing:
function DrawTable() {
$('#table').DataTable( {
"cache": false,
"columnDefs": [
{
"targets": [ 0, 1 ],
"visible": false,
"searchable": true
}
]
} );
}
I was told to use a jsfiddle, so I've uploaded one. Never used this site and my markup is generated but I manually did one.
https://jsfiddle.net/nqeqxzub/9/
Maybe it's too late, but I will put it anyway. After two days of searching all over the web, I find a simple solution without any DataTable functions
<td>
<button type="button" id="{{$lead->id}}" name="{{$lead->id}}" onclick="deleteRecord(this.id,this)" data-token="{{ csrf_token() }}">Delete</button>
</td>
this cell above has an onclick function that takes 2 parameters, the first one (this.id) is the id of the button (that comes from the DB, and will be passed to ajax to update the DB), and the second one (this) which is the index of the button itself (later we will extract the index of the row from it)
function deleteRecord(mech_id,row_index) {
$.ajax({
url:"{{action('MechanicController#destroy')}}",
type: 'get',
data: {
"id": mech_id,
"_token": token,
},
success: function ()
{
var i = row_index.parentNode.parentNode.rowIndex;
document.getElementById("table1").deleteRow(i);
}
});
}
Now in the success function, I have used 2 lines:
the first one is to extract the row index from the button (2 parents because we have to pass from the parent of the button, in this case , and then the parent of the which is the row)
the second line is a simple delete row of our index from table1 which is the name of my table
I am struggling to figure out how to pass a <div id> to another javascript. For example, at the start of my page I have the following script which creates a div id tag that allows me to dynamically select and change content of the page.
$(document).ready(function() {
$("select").change(function() {
var subFolder = $(this).val();
$('#folderName').text(subFolder);
$('#stats').attr('src', '/hardware/' + subFolder + '/stats/usage.txt');
$('#hostInfo').attr('src', '/hardware/' + subFolder + '/stats/host.txt');
$('#folderContent').show();
});
$.ajax({
url: 'getFolders.php',
type: 'GET',
dataType: 'json',
success: function(json) {
var $selectBox = $('#folderList');
$.each(json, function(i, value) {
$selectBox.append($('<option>').text(value).attr('value', value));
});
$selectBox.change();
}
});
});
This allows me to do the following - this creates a selector that a particular folder can be selected.
<div class="hidden-print">
<select id='folderList'></select>
</div>
When the folder list is selected above it allows me to change content like the items below:
like the above to another java script.
$(document).ready(function() {
$('#example3').DataTable( {
"processing": true,
"ajax": {
"url" : "../../reports/drives.txt",
"dataSrc" : ""
},
"columns": [
{ "data": "Hostname.Name" },
{ "data": "Name"}
]
} );
} );
When i select a folder above from the selector i would like the folder under the URL under the AJAX to be modified along with it to update it.
UPDATE
After looking at this a bit further I don't think my explanation fit very well.
$(document).ready(function() {
$("select").change(function() {
var subFolder = $(this).val();
$('#folderName').text(subFolder);
$('#folderLogo').attr('src', '/server/' + subFolder + '/Logo/hardware.png');
$('#folderContent').show();
});
$.ajax({
url: 'getFolders.php',
type: 'GET',
dataType: 'json',
success: function(json) {
var $selectBox = $('#folderList');
$.each(json, function(i, value) {
$selectBox.append($('<option>').text(value).attr('value', value));
});
$selectBox.change();
}
});
});
var thisId = $('folderList').attr('id');
I want to take this variable which should be a single folder and use it on a script like the one below.
var subFolder = $(this).val();
$('#folderName').text(subFolder);
$('#folderLogo').attr('src', '/server/' + subFolder + '/Logo/hardware.png');
I would like to take the "subfolder" and use it something like the following:
$(document).ready(function() {
$('#example3').DataTable( {
"processing": true,
"ajax": {
"url" : "/server/" + subfolder + "/Stats/Map.txt",
"dataSrc" : ""
},
"columns": [
{ "data": "Hostname.Name" },
{ "data": "Name"}
]
} );
} );
I tried to get the method below to get a div id conversion and it doesn't have any data when i try it that way. I should have stated i want to use the variable in the sub folder in the script above... I tried a window.variable name i have tried the global variable and still nothing seems to be working correctly. My guess is that the way the variable is being processed is not carrying over.
You can access the id using $('#folderList').attr('id').
Assign that to a variable and pass it into your function. If you are loading a separate script using $(document).ready(), it may not be available unless it's a global variable.
Something like this might do the trick for you.
var thisId = $('#folderList').attr('id');
$(document).ready(function() {
$('#'+thisId).append('whatever');
} );
You can also pass it inside jQuery function using window.variable = value that will be considered as a global variable for that window object.
With your help i was able to diagnose and find the issue. When the variable is outside of the function it doesn't run. By adding it into the document.ready function it will keep the variable through changes of the dropdown. Then finding that because there are multiple initializations of the data-tables structure - i have to add the "destroy" flag = true. This destroys the old datatables and allows a new one to be created after you change the folder.
$(document).ready(function() {
$("select").change(function() {
var subFolder = $(this).val();
$('#folderName').text(subFolder);
$('#folderLogo').attr('src', '/hardware/' + subFolder + '/Logo/hardware.png');
$('#hdstats').attr('src', '/hardware/' + subFolder + '/hdstats/hdstats.csv');
$('#folderContent').show();
$('#example3').DataTable( {
"destroy": true,
"processing": true,
"ajax": {
"url" : "/hardware/" + subFolder + "/hdstats/stats.txt",
"dataSrc" : ""
},
"columns": [
{ "data": "Hostname.Name" },
{ "data": "Name"}
]
} );
});
$.ajax({
url: 'getFolders.php',
type: 'GET',
dataType: 'json',
success: function(json) {
var $selectBox = $('#folderList');
$.each(json, function(i, value) {
$selectBox.append($('<option>').text(value).attr('value', value));
});
$selectBox.change();
}
});
});
I have a datatable populated with aaData. There is this last column which is action that again is populated with an array.
What i need to do is, by clicking an action link, I should pick up the column array value for that specific row where i clicked the action.
The action column is populated with below json format
[
{
"displayValue":"Browse",
"link":"svnpath/BacklogApp",
"displayIcon" : "browselogo"
},
{
"displayValue":"Source Code",
"link":"svnpath/BackLog/trunk/webapp-project/",
"displayIcon" : "svnlogo"
},
{
"displayValue":"Contributors: Vaibhav",
"link":"#contributors",
"displayIcon" : "people"
}
]
This is my action column which has three links - browse, source code and contributor. When i click the contributor icon, i should be able to get "Contributors: Vaibhav" this string.
Below is the JS code
$(document).on('click', '.contributor', function(e)
var aPos = tableAADataForContributors.fnGetPosition(this);
alert(aPos);
//if aPos returns an array in console, use first val at pos zero to get row data
var aData = tableAADataForContributors.fnGetData(aPos[0]);
alert(aData);
But on alert, my aPos is coming to be null whereas tableAADataForContributors is not null.
Also, this is how I am populating the datatable
$.ajax({
type: "GET",
url: url,
dataType: "json",
cache: false,
contentType: "application/json",
success: function(tablePropJSONData) {
var oTable = $('#genericTable').dataTable( {
"bProcessing": true,
"aaData": tableObj,
"sPaginationType" : "full_numbers",
"bJQueryUI" : true,
"bRetrieve" : true,
"bPaginate" : true,
"bSort" : true,
"aaSorting" : [[ 2, "desc" ]],
"iDisplayLength" : 50,
"bAutoWidth" : false,
"bStateSave" : false,
"aoColumns" : tablePropJSONData.aoColumns,
"fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
var lastColumnIndex = aData.length-1;
var actionColumnContent = renderActionColumn(aData[lastColumnIndex]);
$('td:eq('+lastColumnIndex+')', nRow).html(actionColumnContent);
}
});
tableAADataForContributors = oTable; // initializing for picking up contributors from datatable.
searchDataTable(oTable, searchTerm);
},
And likewise initializing a global variable tableAADataForContributors to be able to use it in onclick event later.
I am not able to do so. Please someone suggest a javascript code.
Thankfully, I was able to solve it myself. Just a little bit of here and there was needed.
Below code does the requirement
$(document).on('click', '.contributor', function(e){
var aPos = tableAADataForContributors.fnGetPosition( $(this).closest('tr')[0]);
//if aPos returns an array in console, use first val at pos zero to get row data
var aData = tableAADataForContributors.fnGetData(aPos);
var actionColumnData = aData[aData.length-1];
$.each(actionColumnData, function(i, value){
alert(value.displayValue)
});