I'm building a Q&A site where one can comment on questions and their answers.Its a threaded commenting system with ajax.
this is the javascript part:
function bindPostCommentHandler()
{
$('.commentFormWrapper form').submit(function() {
var current = $(this);
$.ajax({
type: "POST",
data: current.serialize(),
url: "{% comment_form_target %}",
cache: false,
dataType: "html",
beforeSend:function(xhr){
$('.submit', current).html('<img id="preloader" class="va-mid" src="{{MEDIA_URL}}img/indicator.gif" title="processing.." />');
$('#commentError').remove();
},
success: function(html, textStatus) {
current.parent().replaceWith(html);
bindPostCommentHandler();
},
error: function(xhr, textStatus, errorThrown) {
$('#commentError').remove();
$('.submit', current).html('<input type="submit" name="submit" class="submit-post small-button" value="Submit" />');
if(xhr.status == 400){
current.before('<li id="commentError" class="no-bullet errornote margin10">OOPS ! your comment looked liked a spam. Try again with some modifications.</li>');
}else {
current.before('<li id="commentError" class="no-bullet errornote margin10">Your comment was unable to be posted at this time. You may try after sometime.</li>');
}
//bindPostCommentHandler();
}
});
return false;
});
}
$(document).ready(function() {
bindPostCommentHandler();
});
the html part:
<!-- comment form for question -->
<div class="commentFormWrapper">
{% render_comment_form for question %}
</div>
<!-- comment form for answers -->
{% for answer in question.answers.all %}
<div class="commentFormWrapper">
{% render_comment_form for answer %}
</div>
The problem is, when there is only a single form in a page it works smoothly. With multiple forms its working but sending the request to the server muliple times(grows in multiples).
Also, it would be better to dynamically insert/remove forms. But if I add the html for forms manually, I'll miss out csrf tokens and timestamp fields in the comment form. Anybody has solutions to these ?