jQuery not deleting record from table - javascript

I want to create a new function that when I press a little trashcan icon, a record in MYSQL will be deleted.
The following is my js codeļ¼š
$("table").find("img[class='icon_garbage']").click(function(){
var delnum = $(this).parents("tr").find("td[class='so']").text();
var string='delete_num='+delnum;
$.ajax({
url:"../src/delete.php",
type:"post",
data:string,
success: function(){
var tr = $(this).parents("tr");
tr.fadeOut('slow', function(){
$(this).remove();
});
}
})
});
and it's not working.
the record do delete, but the record does't fadeout.
but if I fix the code as following:
$("table").find("img[class='icon_garbage']").click(function(){
var delnum = $(this).parents("tr").find("td[class='so']").text();
var string='delete_num='+delnum;
var tr = $(this).parents("tr");
tr.fadeOut('slow', function(){
$(this).remove();
});
$.ajax({
url:"../src/delete.php",
type:"post",
data:string,
success: function(){
// var tr = $(this).parents("tr");
// tr.fadeOut('slow', function(){
// $(this).remove();
// });
}
})
});
and it's will working ......
I don't know why , can somebody tell me ?
My OS is MAC OSX 10.8.5,and I use MacVim to be my editor.

Set the context in the ajax call to this. Without setting the context, this does not refer to your element in the success event.
$.ajax({
url:"../src/delete.php",
type:"post",
data:string,
context: this, // <----------------- here
success: function(){
var tr = $(this).parents("tr");
tr.fadeOut('slow', function(){
$(this).remove();
});
}
});

Related

Why when I click on the next page the button edit or delete is not working?

Here is my script. I can edit and delete on the first page, but when I click on next page edit and delete are not working. What seems to be the problem?
<script>
$(function(){
$('.edit').click(function(e){
e.preventDefault();
$('#edit').modal('show');
var id = $(this).data('id');
getRow(id);
});
$('.delete').click(function(e){
e.preventDefault();
$('#delete').modal('show');
var id = $(this).data('id');
getRow(id);
});
});
function getRow(id){
$.ajax({
type: 'POST',
url: 'attendance_row.php',
data: {id:id},
dataType: 'json',
success: function(response){
$('#datepicker_edit').val(response.date);
$('#attendance_date').html(response.date);
$('#edit_time_in').val(response.time_in);
$('#edit_time_out').val(response.time_out);
$('#attid').val(response.attid);
$('#employee_name').html(response.firstname+' '+response.lastname);
$('#del_attid').val(response.attid);
$('#del_employee_name').html(response.firstname+' '+response.lastname);
}
});
}
</script>
Ajax calls are asynchronous.
Before the elements are appended via ajax, the click handler gets registered, which find no elements with $(".edit").
You should probably use event delegation.
Try to change your function:
$(function(){
$('.edit').click(function(e){
e.preventDefault();
$('#edit').modal('show');
var id = $(this).data('id');
getRow(id);
});
$('.delete').click(function(e){
e.preventDefault();
$('#delete').modal('show');
var id = $(this).data('id');
getRow(id);
});
});
To this:
$(function(){
$(document).on('click','.edit', function(e){
e.preventDefault();
$('#edit').modal('show');
var id = $(this).data('id');
getRow(id);
});
$(document).on('click','.delete',function(e){
e.preventDefault();
$('#delete').modal('show');
var id = $(this).data('id');
getRow(id);
});
});
Hope it helps.

Execute function after a delay or kill it in jquery

I use a function to load a page with jQuery but only after a certain delay after hovering over a li. For that I use setTimeout on the mouseover and try to kill it on the mouseleave if the mouse hovered for less than 500ms over the li. However, the jQuery.ajax still launches, so basically, if I hover over all lis, that will launch plenty of xhr even if I stay only 1ms on the li.
var timer2;
var delay2 = 500;
$('body').on('mouseover','li',function(){
timer2 = setTimeout(function() {
var url="res.php";
jQuery.ajax(
{
type: 'POST',
url:url,
success: function(data){
$('#res').html(data);
}
});
}, delay2);
});
$('body').on('mouseleave', 'li', function() {
clearTimeout(timer2);
});
The problem here is simple. You use mouseover, mouseover can fire multiple setTimeouts while you are over the element.
$("div")
.on("mouseover", function(){ console.log("mouseover"); })
.on("mouseenter", function(){ console.log("mouseenter"); });
span { background-color: red;
font-size: 2em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<span>Move mouse here</span> to <span>here</span> to <span>here</span></div>
So each time you move over elements inside of the parent, it fires another mouseover. So if that is the case you will create multiple events. So if you see multiple ajax calls for an li, that may be a reason why.
So change it to mouseenter, next cancel the event inside of enter OR track the events via the li itself and not a global.
$("ul")
.on("mouseenter", "li" function(){
$(this).data("timer", setTimeout( function () {});
}).on("mouseleave", "li" function(){
var id = $(this).data("timer");
if (id) window.clearTimeout(id);
})
And if you really want to be sure, clear the timeout on mouseenter....
Just clear your timeout before setting it again :
var timer2 = null;
$('body').on('mouseover','li',function(){
clearTimeout(timer2);
timer2 = setTimeout(function(){ .....
You need to initialize the timeout to null, otherwise you'll get an error can't clear timeout of undefined.
Also, try this to trigger the mouseleave :
$('body').on('mouseover','li',function(){
// ...
$(this).off("mouseleave").on("mouseleave", () => clearTimeout(timer2))
});
Edit : Working snippet
var timer2 = null;
var delay2 = 2000;
$('body').on('mouseover', 'li', function() {
clearTimeout(timer2);
console.log("Setting timeout...")
timer2 = setTimeout(() => console.log("Ajax call!"), delay2);
$(this).off("mouseleave").on('mouseleave', () => {
console.log("Clearing timeout.")
clearTimeout(timer2);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li>Hover over me</li>
<li>Over me too</li>
Give an id to that specific li and use as below. This works. Check console Networks tab for verification.
var timer2;
var delay2 = 500;
var ajax;
$('body').on('mouseover','li#one',function(){
console.log("Mouse over");
clearTimeout(timer2);
timer2 = setTimeout(function() {
if(ajax) {ajax.abort();}
var url="res.php";
ajax = $.ajax(
{
type: 'POST',
url:url,
async:true,
success: function(data){
$('#res').html(data);
}
});
}, delay2);
});
$('body').on('mouseleave', 'li#one', function() {
console.log("Mouse left");
clearTimeout(timer2);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li id="one">One</li>
<li>Two</li>
There are few ways to solve this problem
abort your request after mouseleave
use variable inside callback to tell it "don't do it"
abort your request
// ...
var request;
$('body').on('mouseover','li',function(){
// ... I omited `setTimeout` to simplify the explanation
// you have to make this variable to be able to control your requests
var xhr = new window.XMLHttpRequest();
// here we save our request
request = jQuery.ajax(
{
// ...
// note this change here, it is required for jquery 3.0 and more
xhr : function(){ return xor; }
});
// ...
});
$('body').on('mouseleave', 'li', function() {
// ...
// now we can `abort` it any time user mouse leaves
request.abort();
});
Question about abort on SO
use variable
// ...
var leaved = false
$('body').on('mouseover','li',function(){
// ... I omited `setTimeout` to simplify the explanation
leaved = false
jQuery.ajax(
{
// ...
success: function(data){
if (leaved) return;
$('#res').html(data);
}
});
// ...
});
$('body').on('mouseleave', 'li', function() {
// ...
leaved = true
});

Track click over iframe by Javascript / Jquery

how can we track clicks on iframe (like any advt.) and record that event in my own database (with ajax) according to website users respectively with advt id and user id
i have tried onclick (like below) event on parent div but not working -
$('div.ad').on('click', function(){
$.ajax({
url: 'clickevent.php',
type: 'POST',
data: {
'id': adId
},
dataType: 'json',
success: function(data){
// show success msg to user
},
error: function(){
// show failure msg
}
});
});
i tried focus and blur while cursor is over that iframe
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
jQuery(function( $ ){
var isOverAd = false;
$( "iframe[ id *= google ]" )
.mouseover(function(){
isOverAd = true;
})
.mouseout(function(){
isOverAd = false;
});
$( window ).blur(
function(){
if (isOverAd){
$.ajax({
url: 'clickevent.php',
type: 'POST',
data: {
'id': adId
},
dataType: 'json',
success: function(data){
//show success msg
},
error: function(){
//show failure msg
}
});
}
}).focus();
});
i have also tried for when window loss blur while mouse on that iframe
i have mapped pixels ($0 values) it is also not working.
but nothing is working ......i will be very thankfull if you help me
To access an frame in page you can do this:
var frame = window.frames['FRAME-ID'];
$(frame).load(function ()
{
$(frame).contents().find('ELEMENT-IN-FRAME');
//To manage click on element body ( or any elements):
$(frame).contents().find('body').on('click', function(){alert('k')});

Masonry items not reloaded when cliking ajax load more button

Hi everyone i have one problem about masonry items.
I have created this DEMO from codepen.io
In this demo you can see there is this javascript code:
$(window).load(function()
{
$( function() {
var $container = $('.posts-holder');
$container.masonry({
isFitWidth: true,
itemSelector: '.kesif-gonderi-alani'
});
});
});
I show only 10 posts when a page is opened. If user want to show other 10 posts then user needs to click (show more button). I created this ajax function for show more posts.
$('.showmore').live("click",function(event)
{
event.preventDefault();
var ID = $(this).attr("id");
var P_ID = $(this).attr("rel");
var URL=$.base_url+'diger_fotograflar_ajax.php';
var dataString = "lastid="+ ID+"&profile_id="+P_ID;
if(ID)
{
$.ajax({
type: "POST",
url: URL,
data: dataString,
cache: false,
beforeSend: function(){ $("#more"+ID).html('<img src="wall_icons/ajaxloader.gif" />'); },
success: function(html){
$("div.posts-holder").append(html).each(function(){
$('.posts-holder').masonry('reloadItems');
});
$("#more"+ID).remove();
}
});
}
else
{
$("#more").html('The End');// no results
}
return false;
});
this code working when clicking showmore button $('.posts-holder').masonry('reloadItems'); but collecting new posts in one place. But when I change the width of the page everything is improving.
I think that you can use $container.masonry(); after adding your elements, like this :
$("div.posts-holder").append(html).each(function(){
$('.posts-holder').masonry('reloadItems');
});
$container.masonry();
You can see it working here.
Hope that can help.
you have to use the appended method of masonry ... otherwise how would it know that you have added any new element.
Adding the elements simply wont align them as masonry doesnt have any event listner for new element added.
var el = $('<div class="kesif-gonderi-alani" style="height:300px;"></div>')
$container.masonry().append( el ).masonry( 'appended',el );
Hers is small demo on codepen http://codepen.io/knaman2609/pen/xbJMRY
Click on the button to append elements dynamically
http://masonry.desandro.com/methods.html

When this ajax jquery trigger I want a image that loads for 1 second

I have this code
<script type="text/javascript">
$(function () {
$(".a").live("click", function () {
var $this = $(this),
ProductImageId = $this.data('ProductImageId');
$.ajax({
url: '/Home/AddToCart',
type: "post",
cache: false,
data: { ProductImageId: ProductImageId },
success: function (data) {
data = eval(data);
$this.addClass('productSelected');
},
error: function (result) {
$(".validation-summary-errors").append("<li>Error connecting to server.</li>");
}
});
});
Every time someone click on this button I want a image to load for like 1 sec
so the user knows that something happened..
any kind of help is appreciated
Something like:
var $loader = $('<img src="loader.gif">').appendTo(document.body);
And then
success: function (data) {
setTimeout(function() {
$loader.remove();
data = eval(data);
$this.addClass('productSelected');
},1000);
}
It will show the image for 1sec + the ajax loading time. Although, as a visitor of your site I would probably prefer to skip the 1sec delay...
Add before send like this :
beforeSend: function(){
$("some element").append("<img src='url' id='one_sec_img' />");
SetTimeout(1000, function(){
$("#one_sec_img").hide();
})
}
But, I think your requirement is something normal :
Here, bcoz of the before send, as soon as you click button that triggers ajax, the image will be loaded, and on success, the image can be hidden . This is the usual process, in this case,setTimeout is not needed . But, if your requirement is something like, the image should appear only one sec, you can use set timeout. Otherwise, below code is enough.
beforeSend: function(){
$("some element").append("<img src='url' id='one_sec_img' />");
},
success: function(res){
$("#one_sec_img").hide();
}
<script type="text/javascript">
$(function () {
$(".a").live("click", function () {
var html=$(this).html();
$(this).html('loading');//<img src="" />
var $this = $(this),
ProductImageId = $this.data('ProductImageId');
$.ajax({
url: '/Home/AddToCart',
type: "post",
cache: false,
data: { ProductImageId: ProductImageId },
success: function (data) {
$(".a").html(html);
data = eval(data);
$this.addClass('productSelected');
},
error: function (result) {
$(".validation-summary-errors").append("<li>Error connecting to server.</li>");
}
});
});
try this.
Use jQuery BlockUI Plugin to show the image, may be it solve your problem.
Try:
$(".a").click( function( ) {
$("#idOfImage").show().delay( 1000 ).hide();
// ajax call
});
else if you only want the image to disappear only after the ajax call
$(".a").click( function( ) {
$("#idOfImage").show();
$.ajax({
// parameters
}).done( function( ) {
$("#idOfImage").hide( );
});
});

Categories