AJAX Delete row in table with PHP id selected - javascript

How would you delete a row from a table using AJAX based on this code?
Here's the PHP code I'm working with:
foreach ($results as $result) {
echo "<tr><td>".$result['first_name']."</td><td>".$result['last_name']."</td><td><button class=\"btn btn-sm btn-danger delete_class\" id=\"".$result['id']."\" >DELETE</button></td></tr>";
}
As you can see, the button has an id paired with it.
Here's my jquery/AJAX code to delete the file from the database:
<script>
var $tr = $(this).attr('parentElement');
$('.delete_class').click(function(){
var del_id= $('.delete_class').attr('id');
$.ajax({
url:"delete_page.php?delete_id="+del_id,
cache:false,
success:function(result){
$tr.find('td').fadeOut(1000,function(){
$tr.remove();
});
}
});
});
</script>
There is also a PHP file that goes into the database and deletes the data, which works fine.
In the javascript code above ^ the variable being set at the top "$tr" is saying the 'parentAttribute' is the "td" not the "tr", how would I go up two parent attributes?
What can I change my "success:function(result){ }" to to make the row immediately disappear, because,
$tr.find('td').fadeOut(1000,function(){
$tr.remove();
}
this code ^ isn't working.

Change your current jquery code as shown below:
<script>
$('.delete_class').click(function(){
var tr = $(this).closest('tr'),
del_id = $(this).attr('id');
$.ajax({
url: "delete_page.php?delete_id="+ del_id,
cache: false,
success:function(result){
tr.fadeOut(1000, function(){
$(this).remove();
});
}
});
});
</script>
The closest method returns the first ancestor of the selected element.
https://api.jquery.com/closest/

HTML
<table>
<thead>
<tr>
<th>Page Name</th>
<th>Page Image</th>
<th>Action </th>
</tr>
</thead>
<tbody>
<tr>
<td>Page Name1</td>
<td>Page Image1</td>
<td><a title="Delete" class="dlt" href="delete.php?id=1" >Delete</a></td>
</tr>
<tr>
<td>Page Name1</td>
<td>Page Image1</td>
<td><a title="Delete" class="dlt" href="delete.php?id=2" >Delete</a></td>
</tr>
</tbody>
</table>
Javascript
<script>
$("a.dlt").click(function(evt){
evt.preventDefault();
if(confirm("It will Delete All detail related to this. Are You Sure? ")){
var dis = this;
$.post($(dis).attr('href'),{'delete':'dlt'},function(resp){
if(resp == 1){
$(dis).parent().parent().remove();
}else{
alert(resp);
}
});
}
});
</script>

Try
tr = $(this).parent();
there's no attribute called 'parentElement' that's why it's not working.
reference: Jquery Docs
I'd also change the function line to:
var del_id = $(this).attr('id');

Related

How do i refresh or redraw table rows

Below is the classical issue which I am facing during my app development.
I have an array of JSONObjects in my spring controller that I have to iterate in the jsp;
Also another status attribute called JSONArrayStatus is set that suggests if JSON array is empty or not.
Using jquery if JSONArray is empty I will show noDataImageDiv otherwise will show tableDIV (Binding the data from JSONArray using JSTL)
The problem I am facing is as below.
1. Edit a row in the table and click on Update. At this time I make an Ajax Call say, "UpdatedUser", which will return all the records along with the updated records. I could use refresh however thats not a recommended user experience and hence a no no.
To reflect the updated users in the table, I use jquery as below
clearing table rows table.clear().draw()
Loop the result set as follows.
redraw code
function reDrawExternalContactUsers(externalUsers) {
table.clear().draw();
var row = "";
$.each(externalUsers, function (i, field) {
row = '<tr><td></td><td></td><td class="edit">edit</td></tr>';
$("#tableDIV").append(row);
});
}
afetr this redraw or refresh process
This function is NOT working
$(".edit").click(function(){
});
This function is working
$("#tableDIV .edit").click(function(){
});
Suggest a better way of refreshing table rows, if any.
<div id="tableDIV">
<table id="tableID">
<thead>
<tr>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
if data exist
loop{
<tr>
<td></td>
<td></td>
<td class="edit">edit</td>
</tr>
} // loops ends
if close
</tbody>
</table>
</div>
<div id="noDataImageDiv"> No data image</div>
html code :
<div id="tableDIV">
<table id="tableID">
<thead>
<tr>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
if data exist
loop{
<tr>
<td class="user-name"></td>
<td></td>
<td class="edit" data-user-id="">edit</td> //set user_id in attr data-user-id
</tr>
} // loops ends
if close
</tbody>
</table>
</div>
<div id="noDataImageDiv"> No data image</div>
jquery code :
you should use click event on document
$(document).on('click', '.edit', function () {
var btn = $(this);
var user_id = btn.attr("data-user-id"); //user_id of user will update
// extra user data
$.ajax({
method: "POST",
url: url,
data: {
'id': id,
// extra data to send
},
success: function (data) {
if (data.status) // successfully user updated
{
var user = data.user;
/* you can set user data like this */
btn.closest('tr').find('.user-name').html(user.name);
}
}
});
});

Add a <tr> element to dynamic table, dynamically without a page refresh, php jquery

I am trying to add a dynamic row to the existing table on click of button, whose rows are dynamically created using output from PHP script.
I doing an ajax call to the script insert_tr.php which returns me a TR element in the same format as the existing table with the data.Data is returned appropriately
But unfortunately, the <tr> row is not being added to the table dynamically but adds only after a page refresh.
PHP file code :
<div id="v_div">
<table class="table table-bordered table-striped" >
<thead>
<th class='col-md-2'>name</th>
<th class='col-md-2'>number</th>
</thead>
<tbody>
<?php
while ($data = pg_fetch_assoc($ret)) {
echo
"<tr id=tr_".$data['sr_number'].">
<td class='td_topic' id=title:".$data['number']." >".trim($data['name'])."</td>
<td class='td_topic' id=title:".$data['number']." >".trim($data['number'])."</td>
<td class='td_topic' id=title:".$data['number']." ><button class='btn btn-info check1' type=button title='Add Entry'>Add Entry</button></td>
</tr>";
?>
</tbody>
</table>
</div>
Javascript :
$(document).ready(function() {
$("#v_div").on('click', '.check1', function() {
var field_userid = $(this).parent().attr("id");
var value = $(this).text();
$.post('insert_tr.php', field_userid + "=" + value, function(data) {
if (data != '') {
$(this).closest("tr").after(data);
}
});
});
});
All I want to do is add the row immediately after the current TR am on ,dynamically without a page refresh, which serves the ultimate use of an ajax call.
The reference to this is not the button that was clicked.
$(this).closest("tr").after(data);
Store a reference to the row outside the Ajax call.
$(document).ready(function() {
$("#v_div").on('click', '.check1', function() {
var field_userid = $(this).parent().attr("id");
var value = $(this).text();
var row = $(this).closest("tr");
$.post('insert_tr.php', field_userid + "=" + value, function(data) {
if (data != '') {
row.after(data);
}
});
});
});

Why I'm not able to call the javascript AJAX function in following scenario? [duplicate]

This question already has an answer here:
How to call an AJAX function on anchor tag?
(1 answer)
Closed 8 years ago.
My code snippet from smarty template is as follows:
<form name="transaction_form" id="transaction_form">
<table class="trnsction_details" width="100%" cellpadding="5" >
<tbody>
<tr>
<td width="150"><b>Transaction Status : </b></td>
<td class="view_details">
<select name="transaction_status_update" id="transaction_status_update">
{if $transaction_status_array}
{foreach from=$transaction_status_array item="status"}
<option value="{$status}" {if $status == $user_transaction_details.transaction_status}selected="selected" {/if}>{$status|capitalize:true}</option>
{/foreach}
{/if}
</select>
</td>
<td width="150">
</td>
</tr>
<tr>
<td valign="top"><b>Remark : </b></td>
<td><textarea name="transaction_remark" cols="30" rows="5"></textarea></td>
<td><a class="edit_user_transaction_status" href="{$control_url}{$query_path}?op=edit_user_transaction&page={$page}&txn_no={$user_transaction_details.transaction_no}&transaction_data_assign={$user_transaction_details.transaction_data_assign}&user_id={$user_id}{if $user_name!=''}&user_name={$user_name}{/if}{if $user_email_id!=''}&user_email_id={$user_email_id}{/if}{if $user_group!=''}&user_group={$user_group}&{/if}{if $user_sub_group!=''}&user_sub_group={$user_sub_group}{/if}{if $from_date!=''}&from_date={$from_date}{/if}{if $to_date!=''}&to_date={$to_date}{/if}{if $transaction_status!=''}&transaction_status={$transaction_status}{/if}{if $transaction_no!=''}&transaction_no={$transaction_no}{/if}">Update</a></td>
</tr>
</tbody>
</table>
</form>
Now I want to call the following jQuery-AJAX function upon clicking on the anchor tag, but I couldn't. I tried to print the alert at the beginning of the function but that is also no getting printed. Can you help me in calling the function upon clicking the hyperlink? Thanks in advance.
$(document).ready(function() {
//This function is use for edit transaction status
$(".edit_user_transaction_status").click(function(e) { alert("Hello");
e.preventDefault();
//for confirmation that status change
var ans=confirm("Are you sure to change status?");
if(!ans) {
return false;
}
var post_url = $(this).attr('href');
var transaction_status_update = $('#transaction_status_update').val();
$.ajax({
type: "POST",
url: post_url+"&transaction_status_update="+transaction_status_update,
data:$('#transaction_form').serialize(),
dataType: 'json',
success: function(data) {
var error = data.login_error;
$(".ui-widget-content").dialog("close");
//This variables use for display title and success massage of transaction update
var dialog_title = data.title;
var dialog_message = data.success_massage;
//This get link where want to rerdirect
var redirect_link = data.href;
var $dialog = $("<div class='ui-state-success'></div>")
.html("<p class='ui-state-error-success'>"+dialog_message+"</p>")
.dialog({
autoOpen: false,
modal:true,
title: dialog_title,
width: 500,
height: 80,
close: function(){
document.location.href =redirect_link;
}
});
$dialog.dialog('open');
}
});
});
});
It looks like you are using Smarty
You need to add JavaScript block between
{literal}
// your javascript or jquery code
{/literal}

Open link when doubleclicking on table row with jQuery

I have a table that looks like this:
<table id="table">
<thead>
<tr class='tablehead'>
<th>Test</th>
</tr>
</thead>
<tbody>
<tr class='tablecell'>
<td>
</td>
</tr>
</tbody>
</table>
I want to be able to double click on a row and then trigger a link.
An ID has to be transmitted somehow. Where should I define this? This allows me to edit the selected row afterwards.
Any idea how to do this?
Do you have any jQuery you've written yet? Here's a headstart...
Define your ID in the row:
<tr id="something">...</tr>
Then use something like this:
$('tr').dblclick(function(){
var id = $(this).attr('id');
//do something with id
})
This may help you:
jQuery(function($) {
$('#table tr').click(function() {
return false;
}).dblclick(function() {
window.location = url;
return false;
});
});
Do you mean something like this:
$(document).ready(function() {
$('.tablecell').click(function() {
return false;
}).dblclick(function() {
window.open("your_url");
return false;
});
});
and you could create a hidden field and populate that field with the id when double clicked.
Working demo: http://jsfiddle.net/Xr7LC/ (created from the sample code you provided)
Use dblclick api http://api.jquery.com/dblclick/
You can use $(this).attr('id') to get the id, and obviously you will define the id in a tag.
jQuery code for dblclick:
$(document).ready(function() {
$('#table >thead > tr').dblclick(function() {
alert('Row dblclicked');
alert($(this).attr('class'));
});
});​

Jquery Datatables - Make whole row a link

This maybe simple, but cant seem to figure it out. Using jquery datatables how can I make each row clickable to just link to a normal page? So if someone moused over any of the row the whole row will hightlight and be clickable and link to whatever url I would want it to link to when clicked.
I've use the fnDrawCallback parameter of the jQuery Datatables plugin to make it work. Here is my solution :
fnDrawCallback: function () {
$('#datatable tbody tr').click(function () {
// get position of the selected row
var position = table.fnGetPosition(this)
// value of the first column (can be hidden)
var id = table.fnGetData(position)[0]
// redirect
document.location.href = '?q=node/6?id=' + id
})
}
Hope this will help.
This did it for me using the row callback.
fnRowCallback: function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {
responsiveHelper.createExpandIcon(nRow);
$(nRow).click(function() {
document.location.href = 'www.google.com';
});
},
$('#myTable').on( 'click', 'tbody tr', function () {
window.location.href = $(this).data('href');
});
where #myTable is the ID of the table, and you need put the href in the tr, like that:
<tr data-href="page.php?id=1">
<th>Student ID</th>
<th>Fullname</th>
<th>Email</th>
<th>Phone</th>
<th>Active</th>
</tr>
It's simple enough to do this with a vanilla <table>, but I don't see why this wouldn't work with a jQuery DataTables one either.
$('#myTableId').on('click', 'tbody > tr > td', function ()
{
// 'this' refers to the current <td>, if you need information out of it
window.open('http://example.com');
});
You'll probably want some hover event handling there as well, to give users visual feedback before they click a row.
You can also use the DataTables plugins api which allows you to create custom renderers.
Very cool: JS addon here
And using the fnDrawCallback
fnDrawCallback: function() {
this.rowlink();
},
You can do that to make row clickable :
<script type="text/javascript">
var oTable;
$(document).ready(function() {
oTable = $('#myTable').dataTable({
"ajax" : "getTable.json",
"fnInitComplete": function ( oSettings ) {
//On click in row, redirect to page Product of ID
$(oTable.fnGetNodes()).click( function () {
var iPos = oTable.fnGetPosition( this );
var aData = oSettings.aoData[ iPos ]._aData;
//redirect
document.location.href = "product?id=" + aData.id;
} );
},
"columns" : [ {
"data" : "id"
}, {
"data" : "date"
}, {
"data" : "status"
}]
});
});
</script>
<table id="myTable" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>#</th>
<th>Date</th>
<th>Status</th>
</tr>
</thead>
<tbody></tbody>
</table>
I think it will be like that
$('#invoice-table').dataTable({
"fnRowCallback": function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
var slug = $(nRow).data("slug");
$(nRow).attr("href", "/invoices/" + slug + "/");
$(nRow).css( 'cursor', 'pointer' );
$(nRow).click(function(){
window.location = $(this).attr('href');
return false;
});
}
});
And the table row like that
<tr class="invoice_row" data-slug="{{ invoice.slug }}">
<td>{{ invoice.ref }}</td>
<td>{{ invoice.campaign.name }}</td>
<td>{{ invoice.due_date|date:'d-m-Y' }}</td>
<td>{{ invoice.cost }}</td>
<td>
<span class="label label-danger">Suspended</span>
</td>
</tr>
This worked fine with me
**I have used a simple solution for this. Add onclick on tr and you are done. Tested with jquery datatable **
<tr onclick="link(<?php echo $id; ?>)">
function link(id){
location.href = '<?php echo $url ?>'+'/'+id;
}
Recently I had to deal with clicking a row in datatables.
$(document).ready(function() {
$("#datatable tbody tr").live( 'click',function() {
window.open('http://www.example.com');
} );
} );

Categories