parents remove doesn't work on appended elements - javascript

I'm trying to remove a div after it the remove link on that div is clicked.
The divs are generated using append after the website is loaded.
Appended HTML:
<div class="reviews">
<div class="row-fluid" id="57">
<div class="span2">
<img src="img/default_male.png" alt="Male Default Photo">
</div>
<div class="span10">
<h6>Test Test</h6>
<img class="rating-stars" src="img/2star.png" alt="2 Stars">
<br>
<p class="comment-info">
<time class="timeago" datetime="2013-09-19 22:49:59" title="Thursday, Sep 19, 2013 - 10:49 PM">5 minutes ago</time>,
remove
</p>
</div>
</div>
My JQuery Code:
$(".reviews").on('click', '.removereview', function() {
var review_id = $(this).parents('.row-fluid').attr('id');
console.log(review_id);
$.ajax({
type: "POST",
url: "event_send.php",
data: "func=remove_review&post_id=" + review_id + "&event_name=" + getUrlVars()["event_name"],
success: function(response){
$(".review-count").html(parseInt($(".review-count").html()) - 1);
$(this).closest('.row-fluid').remove();
}
});
return false;
});
The problem is that the div doesn't get removed although the right ID is chosen by the code.
Any ideas on how to fix the problem?
Thank you

this inside the success handler does not refers the clicked element so your selector $(this).closest('.row-fluid') fails to find the element.
One solution is to use a closure variable self which then will be used inside the success handler
$(".reviews").on('click', '.removereview', function() {
var review_id = $(this).parents('.row-fluid').attr('id');
console.log(review_id);
var self = this;
$.ajax({
type: "POST",
url: "event_send.php",
data: "func=remove_review&post_id=" + review_id + "&event_name=" + getUrlVars()["event_name"],
success: function(response){
$(".review-count").html(parseInt($(".review-count").html()) - 1);
$(self).closest('.row-fluid').remove();
}
});
return false;
});
Another is to use $.proxy() to pass a custom context to the success callback
$(".reviews").on('click', '.removereview', function() {
var review_id = $(this).parents('.row-fluid').attr('id');
console.log(review_id);
$.ajax({
type: "POST",
url: "event_send.php",
data: "func=remove_review&post_id=" + review_id + "&event_name=" + getUrlVars()["event_name"],
success: $.proxy(function(response){
$(".review-count").html(parseInt($(".review-count").html()) - 1);
$(this).closest('.row-fluid').remove();
}, this)
});
return false;
});

I believe you are trying to remove the element you got in review_id; Why not remove it directly?
$('#'+review_id).remove();
correct me if I misunderstood your question.

Related

Receive array from ajax request

Good day, Please check my script first.
$(document).ready(function() {
$("#findmynip").click(function() {
$("#hasilnip").html('<img src="<?=base_url();?>assets_global/images/loader.gif"> Please wait');
var nipnnya = $("#nipnya").val();
$.ajax({
type: "POST",
data: {
nip: nipnnya
},
datatpe: 'json',
url: "<?=base_url();?>registrasi/cek_ada/",
success: function(hslnip) {
if (hslnip) {
alert(hslnip);
$("#name").html(hslnip);
//How do i do this
$("#name").html(hslnip['FullName']);
$("#birthday").html(hslnip['BirthDate']);
} else {
$("#name").html('Failed');
}
}
});
return false;
});
});
What i want to is receive the ajax request to my html.
When i try to console.log(hslnip); the result is {"FullName":"BUNGA","BirthDate":"1994-10-03 00:00:00.000"}. Any help would be appreciated.
What i want to receive is
<div id='name'></div>
<div id='birthday'></div>
I made typo at this part : datatpe: 'json', and i change it to dataType: 'json'. It's working now, thans for helping guys.
You cannot remove an array in your situation. You can use It do build an HTML content which can be displayed in hasilnama element.
Change this:
$("#hasilnama").html(hslnip);
To this for example:
$("#hasilnama").html('<span>Fullname: ' + hslnip.FullName + '</span><br><span>Birthdate: ' + hslnip.BirthDate.substring(0, 10) + '</span>');
var hslnip = {"FullName":"BUNGA","BirthDate":"1994-10-03 00:00:00.000"}
$('#name').text(hslnip.FullName)
$('#birthday').text(hslnip.BirthDate)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='name'></div>
<div id='birthday'></div>
Use hslnip.FullName and hslnip.BirthDate

Toggle data-value after Ajax success without element ID

I have multiple buttons to toggle status of different projects:
<div class="btn-group btn-toggle project_status" data-project-id="1" data-form="project_status" data-value="1">
<button class="btn btn-default active">ACTIVE</button>
<button class="btn btn-primary">CLOSED</button>
</div>
<div class="btn-group btn-toggle project_status" data-project-id="2" data-form="project_status" data-value="1">
<button class="btn btn-default active">ACTIVE</button>
<button class="btn btn-primary">CLOSED</button>
</div>
I need to toggle the data-value between 1 and 2 when ajax post success.
I have tried this so far but without any luck:
$('.project_status').click(function(){
var project_id = $(this).attr('data-project-id');
var project_status_val = $(this).attr('data-value');
var toggle_status = function(){
$(this).find('.btn').toggleClass('active').toggleClass('btn-primary');
if (project_status_val == '1'){
alert(project_status_val);
$(this).attr('data-value','2');
} else {
alert(project_status_val);
$(this).attr('data-value','1');
}
return false;
};
var dataString = 'project_id=' + project_id + '&project_status=' + project_status_val;
$.ajax({
type: "POST",
url: "post.php",
data: dataString,
success: toggle_status
});
$('#sidebar-wrapper').load('sidebar.php');
return false;
});
I have got the alert data value correct. I have got the sidebar reload with updated value (only the first click). But I am not able to change the attribute value so that the next click will send the toggled value.
Please help! Thx
$(this) inside the toggle_status method is not your btn. Inside the method the this keyword refers to the object the method belongs to. In this case Window. As a workaround, I have made a self property before the method to store a reference to the selected $('.project_status') object. I have updated the code so it will work.
https://jsfiddle.net/05akxvx3/1/
$('.project_status').click(function(){
var self = $(this);
var project_id = self.attr('data-project-id');
var project_status_val = self.attr('data-value');
var toggle_status = function(){
self.find('.btn').toggleClass('active').toggleClass('btn-primary');
if (project_status_val == '1'){
self.attr('data-value','2');
} else {
self.attr('data-value','1');
}
alert(self.attr('data-value'));
return false;
};
var dataString = 'project_id=' + project_id + '&project_status=' + project_status_val;
$.ajax({
type: "POST",
url: "post.php",
data: dataString,
success: toggle_status
});
$('#sidebar-wrapper').load('sidebar.php');
return false;
});
You have an extra dash in your $(this).attr() statement.
$(this).attr('data--value','2'); ought to be:
$(this).attr('data-value','2');

jQuery .hide() and .show() not working

I have this code generate dynamically using php code:-
<div class="mailList" id="M_6">
<div class="mailListHeader" id="H_6">
<img style="float:right; display:none;" class="loaderIMG" id="LOADER_6" src="images/preloader.gif">
Sent by <strong>Admin</strong> on <strong>Oct 03 2013 02:53 PM</strong> to <strong>Received Response</strong> for Quarter <strong>3</strong> Year <strong>2013</strong>.<br>
Subject: <strong>Test Mail</strong><br>
</div>
<div class="mailListContent" id="C_6">
<div class="closeContent" id="CC_6">Close [x]</div>
<span id="SPAN_6"></span>
</div>
<div class="mailListFooter" id="F_6">
<span class="mailContentBtn" id="MCBTN_6" style="font-size:11px; color:#09C; cursor:pointer;">
View Content
</span>
<span class="mailListBtn" id="MLBTN_6" style="float:right; font-size:11px; color:#C06; cursor:pointer;">
Successfull-[0] Failed-[4]
</span>
</div>
</div>
Then, user can click View Content or Successfull-[0] Failed-[4] that will make a ajax request than display result in div mailListContent. Below is code for the jquery ajax request:-
$(".mailContentBtn, .mailListBtn").click(function(){
var currentId = $(this).attr('id');
currentId = currentId.split("_");
var actualId = currentId[1];
if($("#C_"+actualId).is(":visible")) {
$("#C_"+actualId).hide("slow","swing");
}
$("img#LOADER_"+actualId).show();
if(currentId[0]=="MCBTN") {
var dataString ="action=getMailContentByID&mailID="+actualId;
} else {
var dataString ="action=getMailListByID&mailID="+actualId;
}
$.ajax({
type: "POST",
url: "include/getMail.php",
data: dataString,
cache: false,
async: false,
success: function(html) {
$("#SPAN_"+actualId).empty();
$("#SPAN_"+actualId).append(html);
$("#C_"+actualId).show("slow","swing");
$("img#LOADER_"+actualId).hide();
}
});
});
The request and the events works fine, the problem is every time user click at View Content or Successfull-[0] Failed-[4] the loading image is not display. As you can see, I give a unique ID for every loading image than only 1 loading image will display on clik. There is no error in inspect code in Google Chrome. How can I solve this?
Thank you.
In your call to $.ajax, change the "async" option to "true". Because in your case, the $.ajax is blocking the ui thread in displaying the loading image as it is executed synchronously.
You have missed:
$(document).ready(function () {
});
try this:
<script>
$(document).ready(function () {
$(".mailContentBtn, .mailListBtn").click(function () {
var currentId = $(this).attr('id');
currentId = currentId.split("_");
var actualId = currentId[1];
if ($("#C_" + actualId).is(":visible"))
$("#C_" + actualId).hide("slow", "swing");
$("img#LOADER_" + actualId).show();
if (currentId[0] == "MCBTN") {
var dataString = "action=getMailContentByID" +
"&mailID=" + actualId;
}
else {
var dataString = "action=getMailListByID" +
"&mailID=" + actualId;
}
$.ajax({
type: "POST",
url: "include/getMail.php",
data: dataString,
cache: false,
async: false,
success: function (html) {
$("#SPAN_" + actualId).empty();
$("#SPAN_" + actualId).append(html);
$("#C_" + actualId).show("slow", "swing");
$("img#LOADER_" + actualId).hide();
}
});
});
})
</script>

jQuery - Updating clicked image in jQuery.ajax().done()

I have a few images, like
<img src="unstarred.png" class="unstarred-button" id="unstarred-1" />
<img src="unstarred.png" class="unstarred-button" id="unstarred-2" />
<img src="unstarred.png" class="unstarred-button" id="unstarred-3" />
<img src="unstarred.png" class="unstarred-button" id="unstarred-4" />
Then I bind this function:
$('.unstarred-button').click(function() {
id = $(this).attr('id').replace(/^unstarred-/, '');
url = '/star.php?id=' + id;
$.ajax({
type: 'GET',
url: url
}).done(function() {
// What should be put here?
});
});
Now I don't know how to go forward. I want to change the src attribute of the clicked image in the done() call, but $(this) doesn't return the image clicked for sure, as $(this).attr('id') is undefined according to alert().
Could someone help me out?
That's because this within the context of done doesn't refer to img. You need to save the context in the click event handler:
$('.unstarred-button').click(function() {
var self = $(this);
id = self.attr('id').replace(/^unstarred-/, '');
url = '/star.php?id=' + id;
$.ajax({
type: 'GET',
url: url
}).done(function() {
self.attr('src', 'something.jpg');
});
});
Also, you don't need jQuery to change the src or an id of a DOM element, you can change the attribute directly, i.e., this.src = 'something.jpg or this.id = 'new_id'.
$('.unstarred-button').click(function() {
var that = this;
var id = this.id.replace(/^unstarred-/, '');
var url = '/star.php?id=' + id;
$.ajax({
type: 'GET',
url: url
}).done(function() {
that.src = 'some/new/src.jpg';
});
});

Jquery ajax addClass issue

First sorry im a big beginner and just experimenting, and I made a similar wall like facebook with oembed.
And would like to add a like, and dislike button too.
I started with the like button, it works, likes, and unlikes too, and the cookie saves the class value perfectly.
My problems is the ajax call, so actually when I click on the like button it overwrites all anchors href val and adds a class to all not on what click.
here is my code
jquery
var cookieLike = "like_"
$('a.like').each(function(){
var id = $(this).attr('href'), cookieLiked = cookieLike + id;
switch($.cookies.get(cookieLiked) ) {
case "unliked":
$(this).removeClass('btn-success');
break;
case "liked":
$(this).addClass('btn-success');
break;
}
}).on('click', function(e){
e.preventDefault()
var likeId = $(this).attr('href');
$.ajax({
url: "<?php echo base_url(); ?>stream/like/" + likeId ,
type: "post",
data: likeId,
dataType: "json",
success: function(like)
{
if(like.likeStatus == "unliked") {
$('a.like').attr('href', likeId).removeClass('btn-success');
$.cookies.set(cookieLike + likeId, 'unliked');
}else if(like.likeStatus == "liked") {
$('a.like').attr('href', likeId).addClass('btn-success');
$.cookies.set(cookieLike + likeId, 'liked');
}
}
});
});
html
<div class="stream-bottom">
Komment
<div class="pull-right like-options">
<i class="icon-thumbs-up" title="tetszik"></i>
<i class="icon-thumbs-down" title="nem tetszik"></i>
</div>
</div>
could please someone point out what i am missing?
Maybe:
.on('click', function (e) {
e.preventDefault();
var button = $(this);
var likeId = button.attr('href');
$.ajax({
url: "<?php echo base_url(); ?>stream/like/" + likeId,
type: "post",
data: likeId,
dataType: "json",
success: function (like) {
if (like.likeStatus == "unliked") {
button.removeClass('btn-success');
$.cookies.set(cookieLike + likeId, 'unliked');
} else if (like.likeStatus == "liked") {
button.addClass('btn-success');
$.cookies.set(cookieLike + likeId, 'liked');
}
}
});
});
Bind the target element (the clicked link) and reference it in the success callback
In the .on('click') callback
var $link = $(this);
In the success callback use
$(this).attr('href', likeId)
instead of
$('a.like').attr('href', likeId)
When you use $("a") or $("a.like") you are referring to the entire set of anchor tags or anchor tags with 'like' as the class name. To specifically use the anchor tag on which you have clicked use $(this) variable.
That will give you the element on which the event got generated and in this case the anchor tag on which you clicked.

Categories

Resources