I want to remove the deleted row from the table but it's not working with me. I tried the below code:
Scenario: When a user click on delete link/button, it sends a delete request and deletes data from Database so it should update the table front end view and should remove the clicked deleted row on success.
// Delete remedy which is linked with a Symptom ( Symptoms Table )
$("a.remedy-row-delete").click(function(e) {
e.preventDefault();
var remedy_id = $(this).attr('data-id');
var dataString = '&id='+remedy_id;
$.SmartMessageBox({
title: "Delete Remedy",
content: "Remedy Entry will be deleted, are you sure ?",
buttons: "[YES][NO]"
}, function (ButtonPress) {
if (ButtonPress === "YES"){
$.ajax({
type: 'POST',
data: dataString,
url: '<?php echo $this->CxHelper->Route('eb-admin-delete-linked-remedy-from-symptom') ?>',
success: function(data) {
$("#deleteMessage").show().delay(5000).fadeOut();
$(this).closest('tr').remove();
}
});
}
else {
$("a.remedy-row-delete").removeClass('alert');
}
});
});
I tried $(this).parent().closest('tr').remove(); also on success but not working.
HTML markup:
<table id="cx-records-table" class="table display table-striped table-bordered" width="100%">
<thead>
<tr>
<th>
Title
</th>
<th>
Delete
</th>
</tr>
<?php foreach($remedies as $key => $remedy){ ?>
<tr>
<td class="all"><?php echo $remedy['title']; ?><br></td>
<td><a class="cx-action remedy-row-delete" href="javascript:void(0)" data-id="{{remedy['id']}}"><i class="fa fa-trash-o"></i></a></td>
</tr>
<?php } ?>
</thead>
<tbody></tbody>
</table>
Thanks
because $(this) inside of ajax function is different than from outside you should do something like this
$("a.remedy-row-delete").click(function(e) {
e.preventDefault();
var remedy_id = $(this).attr('data-id');
var dataString = '&id='+remedy_id;
var $this = $(this) // <--- 1. Add this line
$.SmartMessageBox({
...
}, function (ButtonPress) {
if (ButtonPress === "YES"){
$.ajax({
...
success: function(data) {
...
$this.closest('tr').remove(); // <----change this and will works well
}
});
}
else {
$("a.remedy-row-delete").removeClass('alert');
}
});
});
try this
// Delete remedy which is linked with a Symptom ( Symptoms Table )
$("a.remedy-row-delete").click(function(e) {
e.preventDefault();
var remedy_id = $(this).attr('data-id');
var dataString = '&id='+remedy_id;
var self = this;
$.SmartMessageBox({
title: "Delete Remedy",
content: "Remedy Entry will be deleted, are you sure ?",
buttons: "[YES][NO]"
}, function (ButtonPress) {
if (ButtonPress === "YES"){
$.ajax({
type: 'POST',
data: dataString,
url: '<?php echo $this->CxHelper->Route('eb-admin-delete-linked-remedy-from-symptom') ?>',
success: function(data) {
$("#deleteMessage").show().delay(5000).fadeOut();
$(self).closest('tr').remove();
}
});
}
else {
$("a.remedy-row-delete").removeClass('alert');
}
});
});
Related
I have a MVC web app, in one section i manage the permission for users (such as decide which information the user can see/edit/add/delete ecc...).
For prevent some errors, if the checkbox in the column Admin is checked the others in the row will be disabled, because the group Admin can do everything, same thing with the Manager column, but in this case only the checkboxes on his right will be disabled.
Afeter many researches, i didn't find anything which can be useful for my case
This is my View code:
<body>
<div class="limiter">
<br />
<div class="container-table100">
<div class="wrap-table100">
<div class="table">
<table id="tablePermission">
#{
CEG_dev_labelsEntities db = new
CEG_dev_labelsEntities();
int countY = 1;
//get all groups
var groups = from g in db.Groups
orderby g.group_name
select new
{
g.group_name,
g.group_description
};
<thead>
<tr class="table100-head">
<th class="column1">Username</th>
#foreach (var item in groups)
{
<td><button>#item.group_name</button</td>
}
</tr>
</thead>
foreach (var item in db.Users)
{
<tbody id="myTable">
#{
//get all user's group
var group_list = from g in db.Groups
join ug in
db.UserGroups on g.id_group equals ug.id_group
join u in db.Users on
ug.id_user equals u.id_user
where u.username ==
item.username
select new
{
g.group_name
};
//save the single values in a list
//so all information are more accesible
List<string> group_user_list = new
List<string>();
foreach (var item_ug in group_list)
{
group_user_list.Add(item_ug.group_name);
}
<tr style="cursor:default">
<tdclass="column1">
#Html.DisplayFor(model =item.username)
</td>
#foreach (var itemG in groups)
{
//check the corresponding
//checkbox if user is a member
//of a specific group
if(group_user_list.Contains(itemG.group_name))
{
<td style="padding-left:80px"><input
type="checkbox" checked="checked"
class="chkclass" username="#item.username"
groupname="#itemG.group_name" id="#countY" /></td>
}
else
{
<td><input type="checkbox" class="chkclass"
username="#item.username"
groupname="#itemG.group_name"
id="#countY" />
</td>
}
countY++;
}
</tr>
}
</tbody>
}
}
</table>
</div>
</div>
</div>
</div>
</body>
This is the table:
Any suggestion is appreciate.
Leo.
EDIT
I have this click event on checkboxes for managing user's permissions
$(document).ready(function () {
$('.chkclass').click(function () {
var getchkid = $(this).attr('id');
var isChecked = $('#' + getchkid).is(':checked');
if ($('#' + getchkid).is(':checked') == true) {
// to be send to your call
var username = $(this).attr('username');
var groupname = $(this).attr('groupname');
//here put your call ajax to your action
$.ajax({
type: 'Post',
url: '/UserGroups/AddPermission',
dataType: 'json',
data: {
'usr': username,
'grp': groupname
},
success: function (result) {
$('#' + getchkid).prop('checked', true);
},
error: function (jqxhr, status, exception) {
alert('Exception:', exception);
}
})
}
else {
if ($('#' + getchkid).is(':checked') == false) {
// to be send to your call
var username = $(this).attr('username');
var groupname = $(this).attr('groupname');
//here put your call ajax to your action
$.ajax({
type: 'Post',
url: '/UserGroups/DeletePermission',
dataType: 'json',
data: {
'usr': username,
'grp': groupname
},
success: function (result) {
if (result.error == true) {
alert('Error, must be there at least one
admin');
$('#' + getchkid).prop('checked', true);
}
else {
$('#' + getchkid).prop('checked', false);
}
},
error: function (jqxhr, status, exception) {
alert('Exception:', exception);
}
})
}
}
});
});
Since you're doing a loop where everything is the same, you could do something like this:
https://jsfiddle.net/z2mf8314/1/
$('.chkclass').click(function () {
var getchkid = $(this).attr('id');
var isChecked = $('#' + getchkid).is(':checked');
var username = $(this).attr('username');
var groupname = $(this).attr('groupname');
(getchkid == "1" && isChecked) ? $(this).closest('tr').find('input').not('#1').prop({'disabled': true, 'checked': false }) : $(this).closest('tr').find('input').prop('disabled', false);
if (isChecked) {
// to be send to your call
//here put your call ajax to your action
}
else {
// to be send to your call
//here put your call ajax to your action
}
});
I am appending a button to a row when adding via Ajax and PHP:
var addHistory = function()
{
var patient_medication = $("#patient_medicationn").val();
var disease = $("#disease option:selected").text();
var patient_side_effect = $("#patient_side_effect").val();
var pid = $("#pid").val();
var elem = '<button type="button" class="btn btn-danger btn-sm"
id="delete_disease" name="delete_disease"><i class="fa fa-remove"></i>
</button>';
$.ajax({
url: '../php/history.php',
data: {pid: pid, patient_medication: patient_medication, disease:
disease, patient_side_effect: patient_side_effect},
type: 'POST',
dataType: 'TEXT',
success:function(resp)
{
console.log(resp)
$("#after_th").after("<tr id='resp'><td>"+disease+"</td><td>"+patient_medication+"</td><td>"
+patient_side_effect+"</td><td>"+elem+"</td></tr>")
},
error:function(resp)
{
console.log(resp)
}
})
}
And on click:
$(document).ready(function()
{
$("#add_history").on('click', addHistory);
});
In my php file:
$addHistory = "INSERT INTO history(patient_medication, patient_side_effect, disease, patient_id, clinic_id)
VALUES(:patient_medication, :patient_side_effect, :disease, :patient_id, :clinic_id)";
$ExecAddHistory = $conn->prepare($addHistory);
$ExecAddHistory->bindValue(':patient_medication', $patient_medication);
$ExecAddHistory->bindValue(':patient_side_effect', $patient_side_effect);
$ExecAddHistory->bindValue(':disease', $disease);
$ExecAddHistory->bindValue(':patient_id', $pid);
$ExecAddHistory->bindValue(':clinic_id', $clinic_id);
$ExecAddHistory->execute();
$lastId = $ExecAddHistory->lastInsertId();
echo $lastId;
I am echoeing the last insert ID so I can append it to the newly added <tr> and then if directly the user clicked on the remove button, to delete directly if a mistake happened while adding the history.
Now everything working properly and the new row is appending, but it's remove button does not work at all.
The remove button of already existing rows works fine:
$("#delete_disease ").on('click', function()
{
var elem = $(this).closest('tr');
console.log(elem)
var patient_medication_id = $(this).closest('tr').attr('id');
var pid = $("#pid").val();
if(confirm("Are you sure that you want to remove the selected history?"))
{
$.ajax({
url: "../php/deleteDiseaseFromHistory.php",
type: 'POST',
data: { pmid: patient_medication_id, pid: pid},
dataType: 'TEXT',
success:function(resp)
{
if(resp="deleted")
{
elem.fadeOut(800, function() {
//after finishing animation
});
}
},
error:function(resp)
{
alert("Please try again");
}
});
}
});
You need
$(document).on('click', '#delete_disease ', function(event)
in place of
$("#delete_disease ").on('click', function()
Since the content has been loaded through AJAX.
I have a page that looks like this:
"Default List Name" is the name of the current page displayed. There are two buttons below and then a table which is the Default List table. Once I click Btn1, it will just re-display the default list table, but when I click Btn2, another table will be displayed, replacing the default list table. Let's call the second table "Second List". Once the table changes, the title "Default List Name" will also change to "Second List Name".
I am going to use AJAX for this so that real time button click and displaying of the corresponding table are applied. But I am still new to AJAX so I am having quite a hard time.
Here's my current code:
var title = $("#title").text();
var btn1 = $("#btn1");
var btn2 = $("#btn2");
/** If one of the buttons is clicked after another and then displays a table, the previous ajax that displayed the previous table, will be removed **/
$(document).ready(function() {
btn1.on("click", function() {
displayDefaultList();
});
btn2.on("click", function() {
displaySecondList();
});
});
function displayDefaultList(){
console.log("display default list table");
/*$.ajax({
type: 'GET',
dataType: 'json',
cache: false,
url: 'url to current page (not sure)',
async: false
}).*/
}
function displaySecondList(){
console.log("display second list table");
}
I hope I'm making my self clear and hope you guys can help me.
I just wrote this for you just to show you that you can always show and hide your tables
$(document).ready(function(){
$("#mytable1").show();
$("#mytable2").hide();
$("#button1").click(function(){
$("#text").html("Default List Name");
$("#mytable2").hide();
$("#mytable1").show();
});
$("#button2").click(function(){
$("#mytable1").hide();
$("#mytable2").show();
$("#text").html("Second List Name");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<div id = "text">Default List Name</div>
<button id = "button1">Button1</button>
<button id = "button2">Button2</button>
<table id = "mytable1" border = "1">
<tr>
<td>text1</td>
<td>text1</td>
<td>text1</td>
</tr>
<tr>
<td>text2</td>
<td>text2</td>
<td>text2</td>
</tr>
<tr>
<td>text3</td>
<td>text3</td>
<td>text3</td>
</tr>
<tr>
<td>text4</td>
<td>text4</td>
<td>text4</td>
</tr>
</table>
<br/>
<table id = "mytable2" border = "1">
<tr>
<td>box1</td>
<td>box1</td>
<td>box1</td>
</tr>
<tr>
<td>box2</td>
<td>box2</td>
<td>box2</td>
</tr>
<tr>
<td>box3</td>
<td>box3</td>
<td>box3</td>
</tr>
<tr>
<td>box4</td>
<td>box4</td>
<td>box4</td>
</tr>
</table>
NOW for your ajax, you should just simply hide one of the tables based on the button that was clicked, and then load the data to your specific table. This works for me. Hope it helps :)
Here's AJAX:
$(document).ready(function(){
$("#button1").click(function(){
$("#mytable2").hide();
$.ajax({
url:'app.php',
type: "GET",
data: ""
dataType: 'json',
success: function(data){
$.each(data, function(key, value){
$("table #mytable1").append("<tr><td>" +
"ID :" + value.ID +
"Name :"+ value.Name +
"Age :" + value.Age +
"</td><tr>");
.........
});
}
});
});
$("#button2").click(function(){
$("#mytable1").hide();
$.ajax({
url:'app.php',
type: "GET",
data: ""
dataType: 'json',
success: function(data){
$.each(data, function(key, value){
$("table #mytable2").append("<tr><td>" +
"ID :" + value.ID +
"Name :"+ value.Name +
"Age :" + value.Age +
"</td><tr>");
.........
});
}
});
});
});
I created this fiddle for you: https://jsfiddle.net/8bakcfub/.
Basically, each button click will simulate a call to an API that returns a very simple JSON object. On success, the code parses the response, empties the table and appends a new row to it with the data, and finally changes the title.
Note that the code is pretty much the same for both buttons, except for (a) the JSON returned from AJAX, and (b) the title :)
HTML:
<p id="title">
This title will be replaced...
</p>
<button id="btn1">
First list
</button>
<button id="btn2">
Second list
</button>
<table id="table">
<thead>
<th>Col 1</th>
<th>Col 2</th>
</thead>
<tbody>
</tbody>
</table>
JS:
var btn1 = $("#btn1");
var btn2 = $("#btn2");
$(document).ready(function() {
btn1.on("click", function() {
displayDefaultList();
});
btn2.on("click", function() {
displaySecondList();
});
});
function displayDefaultList() {
$.ajax({
type: 'POST',
dataType: 'json',
url: '/echo/json/',
async: false,
data: {
json: JSON.stringify({
row: [1, 2]
})
},
success: function(result) {
$('#title').text('first list');
$('#table tbody').remove();
var newRow = '<tbody><tr><td>' + result.row[0] + '</td></tr><tr><td>' + result.row[1] + '</td></tr></tbody>';
$('#table').append(newRow);
}
});
}
function displaySecondList() {
$.ajax({
type: 'POST',
dataType: 'json',
url: '/echo/json/',
async: false,
data: {
json: JSON.stringify({
'row': [3, 4]
})
},
success: function(result) {
$('#title').text('second list');
$('#table tbody').remove();
var newRow = '<tbody><tr><td>' + result.row[0] + '</td></tr><tr><td>' + result.row[1] + '</td></tr></tbody>';
$('#table').append(newRow);
}
});
}
I'm updating records in my database using a checkbox in a table. I'm trying to offer 1 Alert after ALL the updates went through, rather than alerting for each individual success call
$('#update').click(function () {
$('#view_26 tbody input[type=checkbox]:checked').each(function() {
var id = $(this).closest('tr').attr('id');
$.ajax({
url: 'https://api.knackhq.com/v1/objects/object_1/records/' + id,
type: 'PUT',
data: {field_1: 'Closed'},
success: function (response) {
alert('updated!');
}
});
Is this possible?
Count your successful calls and compare with the total number of calls.
$('#update').click(function () {
var calls=$('#view_26 tbody input[type=checkbox]:checked').length;
var success=0;
$('#view_26 tbody input[type=checkbox]:checked').each(function() {
var id = $(this).closest('tr').attr('id');
$.ajax({
url: 'https://api.knackhq.com/v1/objects/object_1/records/' + id,
type: 'PUT',
data: {field_1: 'Closed'},
success: function (response) {
success+=1;
if(success==calls) alert('updated!');
}
});
Maybe you should also catch unsuccessful calls.
Can you build and PUT the entire JSON array instead of one row at a time? This, of course, would require modifying your web service to get the record id from the JSON instead of the url. It's a better practice to limit your calls in this manner.
$('#update').click(function () {
var myJSON=[];
$('#view_26 tbody input[type=checkbox]:checked').each(function() {
var id = $(this).closest('tr').attr('id');
myJSON.push({ID:id,field_1:'Closed'});
});
//end of each
$.ajax({
url: 'https://api.knackhq.com/v1/objects/object_1/records/',
type: 'PUT',
data: myJSON,
success: function (response) {
alert('updated!');
}
});
All you need to do is to compare the length of checkboxes against the index to see if they are equal, like below.
$('#update').click(function () {
var checkboxes = $('#view_26 tbody input[type=checkbox]:checked'),
len = checkboxes.length;
checkboxes.each(function(i) {
var id = $(this).closest('tr').attr('id');
$.ajax({
url: 'https://api.knackhq.com/v1/objects/object_1/records/' + id,
type: 'PUT',
data: {field_1: 'Closed'},
success: function (response) {
if (i === len - 1 ) {
alert('updated!');
}
}
});
})
});
Try
$('#update').click(function () {
var elem = $('#view_26 tbody tr input[type=checkbox]:checked');
var res = $.map(elem, function(el, i) {
var id = $(el).closest('tr').attr('id');
console.log(id);
return $.ajax({
url: 'https://api.knackhq.com/v1/objects/object_1/records/' + id,
type: 'PUT',
data: {field_1: 'Closed'}
});
});
$.when.apply($, res)
.then(function() {
alert("updated!");
}, function(jqxhr, textStatus, errorThrown) {
alert(textStatus +" "+ jqxhr.status +" "+ errorThrown);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="update">update</button>
<table id="view_26">
<tbody>
<tr id="0">
<td>
<input type="checkbox" value="">
</td>
</tr>
<tr id="1">
<td>
<input type="checkbox" value="">
</td>
</tr>
<tr id="2">
<td>
<input type="checkbox" value="">
</td>
</tr>
</tbody>
</table>
I'm a bit lost at the moment since my code seems to work but my table is not interested. xD
I'm loading data from my db into a table and i want it to be "auto-updated" every three seconds. My JSON data is correct and the js-console displays the updated data. But my table doesn't want to display it so I have to refresh the entire page. However that's not what I want to do.
Here is my code
(HTML+JS):
<script>
$(document).ready(function() {
setInterval(function() {``
$.ajax({
url: "myStuff.php",
success: function(data) {
console.log(data);
myRecords = $.parseJSON(data);
$("#dynatable").dynatable({
dataset: {
records: myRecords
}
});
}
});
}, 3000);
});
<table id="dynatable">
<thead>
<th>test1</th>
<th>test2</th>
</thead>
<tbody>
</tbody>
</table>
PHP:
$response = array();
while ($zeile = mysqli_fetch_array($db_erg, MYSQL_ASSOC)) {
$response [] = array(
"test1" => $zeile['wasd'],
"test2" => $zeile['wasdf']
);
}
echo json_encode($response);
When I add data to my database the returned JSON data is updated, i see it in the js-console. Problem is that my table doesn't want to display it, it just shows the "old" data.
Any suggestions to solve this?
-------------------------------------------------------------
EDIT:
I got it now! This helped me solve my problem. Thanks for the help! :)
Here is my code:
$(document).ready(function() {
setInterval(function() {
$.ajax({
url: "myStuff.php",
success: function(data) {
console.log(data);
var myRecords = $.parseJSON(data);
var dynatable = $('#dynatable').dynatable({
dataset: {
records: myRecords
}
}).data('dynatable');
dynatable.settings.dataset.originalRecords = myRecords;
dynatable.process();
}
});
}, 3000);
});
this code can also update the table.
<script>
$(document).ready(function() {
var mytable = $("#dynatable");
setInterval(function() {
$.ajax({
url: "do.php",
success: function(data) {
myRecords = $.parseJSON(data);
mytable.dynatable({
dataset: {
records: myRecords
}
});
mytable.data('dynatable').settings.dataset.records = myRecords;
mytable.data('dynatable').dom.update();
console.log(data);
}
});
},
1000);
});
</script>