R
R
rm root2020-05-23 22:34:07
Django
rm root, 2020-05-23 22:34:07

Django 3 + Ajax how to call repeatedly the loop that renders records from the database after adding a new record through the form (Ajax) ???

There is a page with comments, I want the page not to be completely updated when submitting the form, but only a block with comments.

Processed the form using ajax. Everything is filled in the database without refreshing the page, but the cycle does not see the record that was added to the database, it will only display it if the page is refreshed, how to fix it ???
Helping hands please :)


ajax

<script>
    const formID = 'form#formReview';
    $(formID).on('submit', (e) => {
        e.preventDefault();
        $.ajax({
            
            url: '/news/news_detail/comment/{{news.id}}/{{user.id}}/', 
            type: 'POST',
            dataType: 'json',
            data: {
                comment: $(formID + ' #comment').val()
            },
            success: function (data) {
                console.log('success'); 
            }
        })
        $(formID + ' #comment').val('');
    })
</script>


the form itself
<form id="formReview" action="{% if user_display %} {% url 'news:article_comments' news.id user.id %} {% else %} {% url 'news:article_comments' news.id 13 %} {% endif %}" method="POST">
{% csrf_token %}
   <fieldset disabled>
      <div class="form-group">
         <input type="text" name="name" id="disabledTextInput" class="form-control" placeholder="{{ user.username }}">
      </div>
   </fieldset>
   <textarea name="comment" id="comment" class="form-control" rows="3" required></textarea>
   <input class="btn btn-primary form-control mt-2" type="submit" value="залишити коментарий">
</form>


viewcomments
{% for comment in comments %}
<div class="row d-flex my-3" >
<div class="col-md-2">
    <img class="img-fluid" src="{% static 'img/user.png' %}" alt="user">
</div>
<div class="col-md-10 comment">
    <strong>{% if comment.id_user.first_name %}{{ comment.id_user.first_name }}{% else %}{{ comment.id_user.username }}{% endif %}</strong> <br>
    <p>{{ comment.comment }}</p>
    <!--  -->
</div>
</div> 
{% endfor %}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question