Reputation: 4885
So I have a dynamically inserted comment form, and after submitting the form, I ajax it with the server, and append the comment to the comments section, but the appending part isn't working. This is what I have:
$(".action-link-comment").click(function() {
if ($(this).parent().parent().find('.comment-form')[0]){
return false;
}
$(this).parent().parent().append('<div class="comment-form"><form class="comment-input"><input class="input-xlarge comment-val" type="text" placeholder="Write a comment..." style="height:14px;"/><input type="submit" style="position:absolute;left:-9999px;width:1px;height:1px;"/></form></div>');
$(".comment-input").submit(function(event) {
event.preventDefault();
var comment = $(this).find('.comment-val').val();
var post_id = $(this).parent().parent().find('.post-id').html();
$.ajax({
url:'/comment',
type: 'POST',
dataType: 'json',
data : {'p' : post_id,
'data' : comment},
success: function(response, textStatus, jqXHR) {
$(this).parent().parent().siblings('.comments-container').append('<div class="comment"><label class="hover><a href="/user/' + response.userid + '"><strong>' + response.name + '</strong><' + '/a><' + '/label><span class="displaynone comment-id">' + response.comment_id + '</span><span class="comment-content">' + response.data + '</span><div class="comment-actions"><a href="javascript:void(0)" class="c-action"><i class="icon-thumbs-up"></i>Like</a><a href="javascript:void(0)" class="c-action"><i class="icon-thumbs-down"></i>Dislike</a><a href="javascript:void(0)" class="c-action reply"><i class="icon-pencil"></i>Reply</a></div>');
},
});
});
});
And for HTML:
<div class="post-container">
...
<div class="post-actions">
<span class="p-action comment">
<a class="action-link-comment" href="javascript:void(0)">Comment</a>
</span>
</div>
</div>
Upvotes: 0
Views: 899
Reputation: 91349
When using this
inside success
, it does not refer to .comment-input
. Store the reference before making the ajax
call:
$(".action-link-comment").click(function() {
var self = this;
// ...
$.ajax({
// ...
success: function(response, textStatus, jqXHR) {
$(self).parent().parent()...
}
});
});
Upvotes: 4
Reputation: 144729
You should cache your this
object, in the context of the success
function this
doesn't refer to your desired object.
$(".action-link-comment").click(function() {
var $this = $(this);
//....
success: function(response, textStatus, jqXHR) {
$this.parent().parent()
// ...
});
Upvotes: 4