I have jquery code to delete data row by row in my table view. When the user click delete icon, conformation box is popup and have "Yes" and "No" button. If "Yes" the row is delete, if "No" close the conformation box and do nothing. The problem is, let say I have 2 row data like this:-
<tr bgcolor=#ACACAC id='ak1'>
<td align='center'>1.</td>
<td>Data 1</td>
<td>...</td>
<td>...</td>
<td>...</td>
<td align='center'>
<img src='image/DocEdit.png' class='editData' id='ID_16'> <img src='image/DocDelete.png' **class='deleteData'** id='**ID_16**'>
</td>
</tr>
<tr bgcolor=#6D6D6D id='ak1'>
<td align='center'>2.</td>
<td>Data 2</td>
<td></td>
<td></td>
<td></td>
<td align='center'>
<img src='image/DocEdit.png' class='editData' id='ID_17'> <img src='image/DocDelete.png' **class='deleteData'** id='**ID_17**'>
</td>
</tr>
So, when I click delete on Data 1, the ID_16 is past to jquery code. Than I click "No" on conformation box. After that, I click delete on Data 2. Now I click "Yes" on conformation box. Data ID_17 deleted from DB, buat after delete ID_17, my jquery will loop and delete ID_16 and all the data that I try to delete before. It's like queue the delete action for the data that I choose "No" on conformation box. Below is my jquery code.
//.deleteData is class for delete button
$('.deleteData').click(function(){
var idData=$(this).attr('id'); //get data id to delete
//Fade in the Popup for conformation delete
$('#cfm-box').fadeIn(300);
//Set the center alignment padding + border see css style
var popMargTop = ($('#cfm-box').height() + 24) / 2;
var popMargLeft = ($('#cfm-box').width() + 24) / 2;
$('#cfm-box').css({
'margin-top' : -popMargTop,
'margin-left' : -popMargLeft
});
// Add the mask to body
$('body').append('<div id="mask"></div>');
$('#mask').fadeIn(300);
//if button no click, do nothing
//#no refer to the button ID no.
$('#no').click(function(){
$('#mask , .cfm-popup').fadeOut(300 , function() {
$('#mask').remove();
});
});//end #no
//if yes click, delete data from db
//#yes refer to the button ID yes.
$('#yes').click(function(){
//parameter to send for delete WHERE statement
var tahun = $('#tahunSemasa').val();
var suku = $('#sukuSemasa').val();
var dataString = "tahun="+tahun+"&suku="+suku+"&id="+idData+"&action=delete";
$.ajax({
type: "POST",
url: "prestasiProses.php",
data: dataString,
cache: false,
success: function(html)
{
alert(html);
if(html=='true')
{
window.location.href="main.php?a=31&tahun="+tahun+"&suku="+suku+"&act=delete";
}
else
{
alert("Failed!");
}
}
});
$('#mask , .cfm-popup').fadeOut(300 , function() {
$('#mask').remove();
});
});//end #yes
});//end .deleteData
Any ideas why this code loop like that?
Thanks for the help
You shouldn't have all that code inside your $('.deleteData').click(function(){. Check out this fiddle to see how I think you should have your code laid out. Notice that I have made the idData a global variable and moved your $('#no').click(function(){ and $('#yes').click(function(){ code to the bottom. My fiddle isn't working because it doesn't have all your includes, but should show you what I mean.
I also moved your mask removal inside your ajax success handler as it seems like you want that to run once your ajax comes back. Is that the case?
EDIT:
The problem you are having is because you are binding to items with the deleteData class multiple times.
When you run the selector $('.deleteData').click(, you are saying, "get each instance of an element with the class 'deleteData' and then bind this function to it." Since you then had the $('#no').click( and $('#yes').click( INSIDE your $('.deleteData').click( you were binding your $('#no').click( and $('#yes').click( twice. If you had three instances of the 'deleteData', your ajax code would have run 3 times.
The problem is that everytime you click deleteData you will bind click to yes and no, to if you click deleteData twice, you bind click to yes and no twice, because it's inside deleteData click event.
So, to prevent this behaviour you have to remove it from inside deleteData event.
You can try this demo.
Type how many binds do you want
Click some text
See how many times it logs the value
Related
I have fetched the values(card details) from an array and put them in an html table, I have also added the delete button for deleting the particular card.
I am deleting this through ajax. When i click on the delete button of the first row, it works perfect but when i click on the other delete buttons from 2nd or 3rd row, there is no action.
Please suggest the correct path to sort out this problem.
Thanks in advance
Here is my code
<tr>
<td><?php echo $val['last4'];?></td>
<td><?php echo $val['exp_month'];?></td>
<td><?php echo $val['exp_year'];?></td>
<td><button id = "del">Delete</button></td>
</tr>
Ajax part
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<script>
$('#del').click(function() {
//var a=document.getElementById("").value;
var val0 = $('#id').val();
var val01 = $('#cust').val();
var fade = document.getElementById("fade");
var show = function(){
fade.style.display = "block";
}
show();
$.ajax({
type: 'POST',
url: 'mywebsite.com/deleting.php',
data: { card_id: val0,cust_id: val01 },
success: function(response) {
fade.style.display = "none";
// alert(response);
mystring = response.replace(/^\s+|\s+$/g, "");
$('#result11').html(mystring);
}
});
});
</script>
You have the same id on your buttons. Id's must be unique within the html document and can not be shared between multiple elements. Read more about the html id attribute
Change the button to use a class instead:
<td><button class="del">Delete</button></td>
Then change your jQuery to bind to that class instead:
$('.del').click(function(e) {
// Since we're using ajax for this, stop the default behaviour of the button
e.preventDefault();
// Get the value from the clicked button
var val0 = $(this).val();
I also added the event e in the function call, and stopped the default behaviour of the button (which is to submit the form) when it's clicked.
You need to give delete buttons a class and bind event on that class not with id. Then on bind function select values from that row elements and then pass them to Ajax.
Here goes my problem: this is the table
I want to click on delete column of a particular row say row no2 then I should select the value OFFICED-Id of that particular row row no.2
The problem is that table is being generated dynamically by the following code
<tbody>
<?php for($i=0;$i<count($detail1);$i++):?>
<tr>
<td><?=$detail1[$i]['id'];?></td>
<td><?=$detail1[$i]['officer_id'];?></td>
<td><button onclick='alert("<?=$detail1[$i]['password']?>")' > change</button></td>
<td><i class=" del glyphicon glyphicon-minus"></i></td>
</tr>
<?php endfor; ?>
</tbody>
I am trying to select that particular cell of a row by applying this jQuery function but I am getting error in the console and it's not working too
the variable id is going to save that particular cell value
$(document).ready(function(){
$(".del").click(function(){
var answer = confirm ("Are you sure you want to delete from the database?");
var id= <?php echo $detail1[$i]['id'];?>;
if (answer)
{
// your ajax code
$.ajax({
type: 'POST',
url: '<?php echo base_url(); ?>Admin/del', //We are going to make the request to the method "list_dropdown" in the match controller
data: {'id':id}, //POST parameter to be sent with the tournament id
//With the ".html()" method we include the html code returned by AJAX into the matches list
success: function(resp) {
alert('you have successfully deleted');
},
error: function(resp) {
console.log('error');
console.log(arguments);
}
});
}
});
});
The error in the console is
SyntaxError: expected expression, got '<'
What I figured out that this line var id= <?php echo $detail1[$i]['id'];?> is causing error and making my jQuery call not functioning
Is there alternative to select that particular cell OFFICED OF A ROW from a dynamic table by any event?
var id= <?php echo $detail1[$i]['id'];?>
Looks like $i is not defined, so id should be null. And so the issue.
Select id something like this. Please test, might need extra work:
var id= $(this).closest('tr').find('td.id').html();
And HTML <td> of id line should look something like:
<td class="id"><?=$detail1[$i]['id'];?></td>
I've got a table which is listing orders and I want to add the possiblity to filter results. Therefore I created a select field and an onchange effect in Jquery which is loading the same table with those filtered results into my Div. Therefore I used Ajax to update this "new Content" to my div. The problem is, that this table has several JQuery effects (for example a slide down when you click on a row) which doesn't work when the Content got created by the AjaxRequest. I have read some things already here in Stackoverflow and in other boards, but there was so many specific cases that I couldn't use any. I've heared something about a "init-function" which I need to call somewhere, so the JQuery things will also work on my Ajax generated content.
This is my Ajax Request:
$('.category').on('change', function (e) {
var optionSelected = $("option:selected", this);
var valueSelected = this.value;
$.ajax({
type: "POST",
url: "includes/listorders.php",
data: "filter=" + valueSelected,
success: function( data ) {
$( "#latestOrders" ).html(data);
}
});
});
This is what my listorders.php basically returns (probably not necessary to know to fix my issue):
$filter = $_POST['filter'];
//Prepare Queries
$lastOrders = "SELECT * FROM Orders ORDER BY dateAdded DESC LIMIT 0,48";
$ps_orders = $db->query($lastOrders);
$data = $ps_orders->fetchAll();
foreach($data as $row)
{
$orderid =$row['id'];
$username = $row['name'];
$done = $row['refsDone'];
$quantity = $row['quantity'];
$running =$row['refsRunning'];
$untouched = $quantity - ($done+$running);
?>
<tr class="header mySlideToggler" data-id="<? echo $orderid ?>">
<td class="align-center">TEST<? echo $username ?></td>
<td>0 %</td>
<td>22 Aug 2014</td>
<td><? echo $done . " / " . $quantity ?></td>
<td><? echo $running ?></td>
<td><? echo $untouched ?></td>
<td>
</td>
</tr><tr style="padding: 0"><td colspan="7" style="padding: 0">
<div class="accounts" style="display: none">
</div>
</td></tr>
<?
}
?>
My Slide effect including another Ajax request for the content which should be displayed into the slided div:
// Slide effect for listing account information to an order
$('.mySlideToggler').click(function( event ){
event.preventDefault();
event.stopPropagation();
var id = $(this).data('id');
var div = $(this).closest('tr').next().find('.accounts');
$.ajax({
type: "POST",
url: "includes/listaccounts.php",
data: "orderid=" + id,
success: function( data ) {
div.html(data);
}
});
$(this).closest('tr').next().find('.accounts').slideToggle();
});
You need to make sure to use the new live version of event listeners, to work with content loaded asynchronously
$('body').on('click', '.my-class', function(){
//handle click event for .my-class here
});
The above code is not specific to your situation, since you have not posted the js code that is not working on async content. It's just a sample of how you manage live event listeners.
Specific answer after reviewing your code update:
$('body').on('click', '.mySlideToggler', function(event){
//do toggle stuff here
});
Why?
The jQuery .click does not support events happening on content loaded asynchronously. The same problem applies to using the following code:
$('.mySlideToggler').on('click', function(event){
//THIS WONT WORK WITH ASYNC CONTENT
});
This is why jQuery has allowed us to register the event on a parent element that was not loaded asynchronously and the provide a second argument to .on that tells us which child of that element to listen for as a target or said event. This works with all events, click|change|focus|blur|etc...
Why $('body')
I generally attach these live handlers to the body of the html document because the body is rarely reloaded via async content, as reloading the entire content would probably warrant a new page load, however it's not necessary to use body. You can attach to any parent element that is static on the page, including document or window
Nice to know
jQuery formerly used the method .live() which has been deprecated for a while now, I think since 1.7
I suggest you read more about the change to .live here: http://api.jquery.com/live/
I hope this has sufficiently answered your question. Let me know if you're still having trouble.
Performance Concern
Attaching the parent object of the .on event as close to the child element as possible will increase performance if you are using a large number of these events, as jQuery doesn't have to traverse as far down the DOM Tree to find the child element.
More info here: http://api.jquery.com/on/#event-performance
I am fetching a problem though I know it's not a big issue, but something is different to me as I new. I have a page which has a list of records, fetching from a database. Now one button is there , after clicking the records, one pop up will be opened up along with some data. Inside that pop up one another link is there called "restore", whenever , that linked will be clicked out the database has been updated. Now up to this its okay for me. But whenever, I close the pop up, my list of records should automatically changed as some records have been restored. But I am not getting the result until and unless I do not refresh the page. so how can I do this, please help me ....
$(function() {
$(".delete").click(function() {
$('#load').fadeIn();
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = 'id='+ id ;
$.ajax({
type: "POST",
url: "restore-request-process.php",
data: string,
cache: false,
success: function(){
commentContainer.slideUp('slow', function() {$(this).remove();});
$('#load').fadeOut();
}
});
//return false;
});
});
in the restore-request-process.php page I just update the database and echo the id.
After the database update, call a function to update the front end or simply reload page using location.reload()
you need to have declared global function in parent window
function Update(){
//global function in parent, update div
}
on popup window call function
window.opener.Update();
that will automatic reload your div, and not all page, If it's not necessary
Suppose this is your listing format
<table>
<?php
foreach($results as $result) { ?>
<tr id="my_div">
<td><?php echo $result->name?></td>
<td class="delete" id="<?php echo $result->id?>"><img src="delete.png"/></td>
</tr>
<?php } ?>
</table>
In restore-request-process.php write a query which fetch all the result from database and just echo the result like this
$result = mysql_query("SELECT * FROM my_table");
while($row = mysql_fetch_array($result))
{
echo '<td>'. echo $row["name"].'</td>
<td class="delete" id="'. echo $row["id"].'"><img src="delete.png"/></td>' ;
}
and onsuccess replaced all the content inside the my_div with response text
CODE IS NOT TESTED
for more references you can go through this link
My JavaScript is as follows:
$.get("/<page>.php", "userid='.$userid.'&"+status, function(data){
$("#status").show("fast").html(data).delay(4000).hide("fast");
});
I have many links on a page that will load this jQuery AJAX and display the status in a div correctly. It all works fine, except if a user click many of the links really fast. The data changes correctly, but the animations are delayed. I've tried including the jQuery stop() and stop(true) and stop(true, true) before the .show but it doesn't seem to help much. Animations can continue long after the last click; for example, if a user clicks 20 times, and then pauses, the hide animations seem to continue long afterwards, despite the stop(). What I want is if a user clicks on another link that causes the AJAX to cause a status display, the basically "resets" the status animations.
Any ideas?
Here's the full relevant JavaScript:
<script type="text/javascript">
...
$(document).ready(function () {
$("#entry a.styled").live("click", function(event){
var status = $(this).attr("rel")+"&game="+$(this).attr("name");
var teamid = $(this).attr("rel");
var gameid = $(this).attr("name");
$("[name="+gameid+"]").show(1);
$(this).hide(1);
$("[rel=t"+teamid.replace("pick=", "")+"]").removeClass();
$("[name=t"+gameid+"]").removeClass();
$("#t"+teamid.replace("pick=", "")).addClass("hilite");
$.get("/<filename>.php", "userid=1&"+status, function(data){
$("#status").stop(true, true).show("fast").html(data).delay(4000).hide("fast");
});
});
</script>
and some relevant HTML, this is within a larger table:
<tr class="row-a">
<td>8-man</td>
<td>1:00 pm</td>
<td class="hilite" id="t298" rel="t233" name="t3235">La Veta</td>
<td>Pick</td>
<td><img src="/images/delete.png" height="12" width="12" /></td>
<td>Pick</td>
<td id="t233" rel="t298" name="t3235">South Park**</td>
<td> </td>
</tr>
The user would click on the "Pick" link or the delete Image which calls the jQuery AJAX get.
Any other improvements to my (limited shown) code are appreciated as well.
jquery version:1.4.2
jqueryui version:1.7.2
Maybe stop() doesn't clear the delay() -- have you tried the .clearQueue() method?
alternatively, you could try with setTimeout rather than delay()...
// animInProgress and animDelay are global variabes
var animInProgress = false;
var animDelay;
//later, in your $.get success function...
$("#status").show("fast").html(data);
if(animInProgress) {
clearTimeout(animDelay);
}
animInProgress = true;
animDelay = setTimeout(function() {
$("#status").hide("fast");
animInProgress = false;
}, 4000);