I'm trying to add comment using ajax. Here is my ajax code:
$(document).ready(function(){
$("#add_comment").click(function(event){
event.preventDefault();
var article_id = {{article.id}};
$.ajax({
url: "http://127.0.0.1:8000/articles/addcomment/" + article_id + '/',
type: "get",
success: function(result){
if(result === "validation error"){
alert(result);
}else{
var data = JSON.parse(result);
$("#comment_block").append("<div class = "comment"><span>" + data['owner'] + "</span><p>" + data['comment_text'] + "</p></div>");
}
}
});
});
});
Here is my form of adding comment in django template:
</div>
{% if username %}
<form action="/articles/addcomment/{{ article.id }}/" method="post" id = "comment_form">
{% csrf_token %}
{{ form }}
<input type="submit" class="button" value="Добавить комментарий" id = "add_comment">
</form>
{% endif %}
</div>
Trying to debug, I noticed that it doesn't even step into ajax body. What am I doing wrong then? I've done ajax query with counting likes and had success in that.
Change to the following:
JS Code:
$(document).ready(function(){
$("#comment_form").submit(function(event){
event.preventDefault();
var article_id = $(this).find('.article_id').value();
$.ajax({
url: "http://127.0.0.1:8000/articles/addcomment/" + article_id + '/',
type: "post",
success: function(result){
if(result === "validation error"){
alert(result);
}else{
var data = JSON.parse(result);
$("#comment_block").append("<div class = 'comment'><span>" + data['owner'] + "</span><p>" + data['comment_text'] + "</p></div>");
}
}
});
return false;
});
});
Django Template:
</div>
{% if username %}
<form action="/articles/addcomment/{{ article.id }}/" method="post" id = "comment_form">
{% csrf_token %}
{{ form }}
<input type="hidden" class="article_id" value="{{ article.id }}" />
<input type="submit" class="button" value="Добавить комментарий" id = "add_comment">
</form>
{% endif %}
</div>
Try this
</div>
{% if username %}
<form action="#" method="post" id = "comment_form">
{% csrf_token %}
{{ form }}
<input type="text" name = "article" value="{{ article.id }}" id = "article_id">
<input type="text" name = "comment" value="comment goes here" id = "comment_text">
<input type="submit" class="button" value="???????? ???????????" id = "add_comment">
</form>
{% endif %}
</div>
$(document).ready(function(){
$("#add_comment").click(function(event){
event.preventDefault();
var article_id = $('#article_id').val();
$.ajax({
url: "http://127.0.0.1:8000/articles/addcomment/" + article_id + '/',
type: "POST", /*i belive you are posting data to BE api*/
data:{'comment':"your comment goes here"}, /* use this get what given in input $("#comment_text").val()*/
success: function(result){
/*process data after success call*/
}
});
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.