What I am trying to do ?
I am trying to display a comment after posting it without page refresh.
What is the problem ?
I am able to successfully post the comment but I am not able to display it without page refresh.
My code:-
html
// This is where you can write a comment.
<form id='articleCommentForm'>{% csrf_token %}
<textarea placeholder='write comment'></textarea>
<button type="submit"> Comment </button>
</form>
// This is where previous comments get displayed
{% for comment in comments %}
<br /> <br />
<div class="row" class="commentStyle">
<div class="col-xs-10">
<span class="userName"> {{ comment.user }} </span>
<br /> <br />
<div class="comment-box">
<textarea class="form-control" readonly> {{ comment.text }} </textarea>
</div>
<br />
<div class="row">
<div class="col-xs-6">
<span class="comment-footer-text"> {{ comment.date }} </span>
</div>
<div>
<div class="comment-control">
<span> {{ comment.likes }} </span>
<span></span>
</div>
</div>
</div>
</div>
</div>
{% endfor %}
ajax
$('#articleCommentForm').on('submit',function(e){
e.preventDefault();
$.ajax({
type: 'POST',
url: '/articles/postComment/',
data: {
'comment': $('#articleCommentForm textarea').val(),
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
},
dataType: 'json',
success: function(data){
var comment = JSON.parse(data['comment']);
$('.commentStyle .userName').val(comment.user);
$('.commentStyle textarea').val(comment.text);
$('.commentStyle .comment-footer-text').val(comment.date);
$('.commentStyle .comment-control span:first-child').val(comment.likes);
}
});
)};
views.py
def postComment(request):
if request.user.is_authenticated():
comment = Comment()
comment.user = request.user
comment.text = request.POST.get('comment')
comment.date = datetime.now()
comment.save()
curComment = serializers.serialize('json', [comment])
data['comment'] = curComment
return JsonResponse(data)
Any help would be highly appreciated.