A
A
Adilet Usonov2020-12-13 09:15:56
Django
Adilet Usonov, 2020-12-13 09:15:56

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>

ajax:
{% 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>

views.py:
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

1 answer(s)
A
Andrew, 2020-12-13
@Adilet-novichok

$('#formname').submit(function(e){
And so?
https://api.jquery.com/submit/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question