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
Related
I need to update the information in a specific row in the google spreadsheets.
I get the data from the inputs in the front end, and the number of the row that I need to update from the userID.
I tried to use ajax, sending the URL of the form response, but what it does is adding a new row.
Is there a way to send the data and the row ID, so I can update that row in the google sheet?
I use tabletop.js to get/read the data from the google sheets, but dont know if it work to update
function Update() {
var ID = userID;
$.ajax({
url: 'https://docs.google.com/forms/d/e/key/formResponse?',
data: {
"entry.2085722051": v_NAME
},
type: "POST",
dataType: "xml",
success: function (d) {
},
error: function (x, y, z) {
$('#success-msg').show();
$('#form').hide();
}
});
}
I expect the function Update() to update the row [number] on the google sheet by using the [number ID] of the user.
But what actual happens is that the function save the data in a new row.
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();
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();
});
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" });
I wrote a little chat plugin that i'll need to use on my site. It works with a simple structure in HTML, like this:
<div id="div_chat">
<ul id="ul_chat">
</ul>
</div>
<div id="div_inputchatline">
<input type="text" id="input_chatline" name="input_chatline" value="">
<span id="span_sendchatline">Send</span>
</div>
There's a 'click' bound event on that Span element, of course. Then, when the user inserts a message and clicks on the "Send" span element, there's a Javascript function with calls an Ajax event that inserts the message into the MySQL database:
function function_write_newchatline()
{
var chatline = $('#input_chatline').val();
$.ajax
({
type: "POST",
url: "ajax-chat-writenewline.php", //1: ok, 0: errore
data: ({'chat_line': chatline}),
dataType: "text",
cache: false,
success: function(ajax_result)
{
function_get_newchatlines();
}
});
}
And, in case the message is successfully inserted into DB, it calls a function to read new lines and put them in HTML structure i posted before:
function function_get_newchatlines()
{
$.ajax
({
type: "POST",
url: "ajax-chat-loadnewlines.php", //1: ok, 0: errore
data: '',
dataType: "text",
cache: false,
success: function(ajax_result) //example of returned string: 'message1>+<message2>+<message3'
{
//explode new chat lines from returned string
var chat_rows = ajax_result.split('>+<');
for (id_row in chat_rows)
{
//insert row into html
$('#ul_chat').prepend('<li>' + chat_rows[id_row] + '</li>');
}
$('#span_sendchatline').html('Send');
}
});
}
Note: 'ajax_result' only contains html entities, not special chars, so even if a message contains '>+<', it is encoded by the php script called with Ajax, before being processed from this JS function.
Now, comes the strange behaviour: when posting new messages Opera, Firefox and even IE8 works well, as intended, like this:
But, when i open Chrome window, i see this:
As you can see, in Chrome the messages are shown multiple times (increasing the number each time, up to 8 lines per message). I checked the internal debug viewer and it doesn't seem that the "read new lines" function is called more than one time, so it should be something related to Jquery events, or something else.
Hope i've been clear in my explanation, should you need anything else, let me know :)
Thanks, Erenor.
EDIT
As pointed out by Shusl, i forgot to mention that the function function_get_newchatlines() is called, periodically, by a setInterval(function_get_newchatlines, 2000) into Javascript.
EDIT2
Here's is a strip of the code from the PHP file called by Ajax to get new chat lines (i don't think things like "session_start()" or mysql connection stuff are needed here)
//check if there's a value for "last_line", otherwise put current time (usually the first time a user logs into chat)
if (!isset($_SESSION['prove_chat']['time_last_line']) || !is_numeric($_SESSION['prove_chat']['time_last_line']) || ($_SESSION['prove_chat']['time_last_line'] <= 0))
{
$_SESSION['prove_chat']['time_last_line'] = microtime(true);
}
//get new chat lines
$result = mysql_query("select * from chat_module_lines where line_senttime > {$_SESSION['prove_chat']['time_last_line']} order by line_senttime asc; ", $conn['user']);
if(!$result || (mysql_num_rows($result) <= 0))
{
mysql_close($conn['user']); die('2-No new lines');
}
//php stuff to create the string
//....
die($string_with_chat_lines_to_be_used_into_Javascript);
Anyway, i think that, if the problem was this PHP script, i would get similar errors in other browsers, too :)
EDIT4
Here's the code that binds the click event to the "Send" span element:
$('#span_sendchatline').on('click', function()
{
//check if there's already a message being sent
if ($('#span_sendchatline').html() == 'Send')
{
//change html content of the span element (will be changed back to "send"
//when the Ajax request completes)
$('#span_sendchatline').html('Wait..');
//write new line
function_write_newchatline();
}
//else do nothing
});
(Thanks to f_puras for adding the missing tag :)
I would do one of the following:
option 1:
stop the timer just before the ajax call in function_write_newchatline() and start the timer when the ajax call returns.
function function_write_newchatline()
{
var chatline = $('#input_chatline').val();
stop_the_timer();
$.ajax
({
type: "POST",
url: "ajax-chat-writenewline.php", //1: ok, 0: errore
data: ({'chat_line': chatline}),
dataType: "text",
cache: false,
success: function(ajax_result)
{
function_get_newchatlines();
},
complete: function() {
start_the_timer();
}
});
}
option 2:
Not call function_get_newchatlines() at all in the success event of the ajax call. Let only the timer retrieve the chat entries.
function function_write_newchatline()
{
var chatline = $('#input_chatline').val();
$.ajax
({
type: "POST",
url: "ajax-chat-writenewline.php", //1: ok, 0: errore
data: ({'chat_line': chatline}),
dataType: "text",
cache: false,
success: function(ajax_result)
{
// do nothing
}
});
}
I think there is some race condition between the function_get_newchatlines() that is called after a chat entry is added by the user and the periodical call of function_get_newchatlines() by the timer.
option 3:
Use setTimeout instead of setInterval. setInterval can mess things up when the browser is busy. So in the end of the setTimeout function call setTimeout again.