Answer the question
In order to leave comments, you need to log in
Django and ajax not working?
The fact is that the page generally reloads, I tried to remove the form tag, it also doesn’t work, I
tried to move the button outside the form. Already searched the Internet, help!
Here is the code: html
<form class="form-wrapper" id='formname' method='POST'>
{% csrf_token %} -->
<input type="text" class="form-control" placeholder="Your name" name='username' id='username'>
<textarea class="form-control" placeholder="Your comment" name='comment' id='comment'></textarea>
<button type="submit" class="btn btn-primary" id='sent'>Submit Comment</button>
</form>
{% load static %}
<script type="text/javascript" src="{% static 'jquery.min.js' %}"></script>
<script type="text/javascript">
$('#sent').submit(function(e){
e.preventDefault();
$.ajax({
type: 'POST',
url: '{% url "leave_comment" data.pk %}',
headers: {'X-CSRFToken': '{{ csrf_token }}'},
data: $('#comment').val(),
dataType: 'json',
success: function(data)) {
alert('success');
}
})
</script>
def leave_comment(request, idd):
if request.is_ajax and request.method == 'POST':
x = Article.objects.get(pk=idd)
x.comment_set.create(username = 'admin', comment = request.POST['comment'])
x.save()
return JsonResponse({'data': 'something'}, safe=False)
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question