I have an $.ajax() call to increase the height of my div every time .comment_form
is submitted (ajax comment). So this works fine but it doesn't save the new height
so when I refresh the page it reverts back to its initial height. Here's my js:
base.js
$('.comment_form').on('submit', function(e) {
e.preventDefault();
var url = window.location.href.split('?')[0];
$.ajax({
type: 'POST',
url: url,
data: {
text: $('.comment_text').val(),
csrfmiddlewaretoken: $("input[name='csrfmiddlewaretoken']").val(),
},
success: function(data) {
console.log(data.text_length);
if(data.text_length < 15) {
var increaseHeight = 30;
}
else {
increaseHeight = (data.text_length) + 20;
}
$('.commentsContainer').append("<div class='comment_div'><h3>" + data.username + "</h3><p>" + data.text + "</p></div>");
$('.commentsContainer').css('height', '+=' + increaseHeight);
},
});
css
.commentsContainer {
height: 600px;
}
django views.py
...
ajax_comment = request.POST.get('text')
comment_length = len(str(ajax_comment))
comments = Comments.objects.all()
if request.is_ajax():
if comment.is_valid():
comment = Comments.objects.create(comment_text=ajax_comment, author=str(request.user))
comment.save()
username = str(request.user)
return JsonResponse({'text': ajax_comment, 'text_length': comment_length, 'username': username})
return render(request, 'article.html', context)