Nurzhan Nogerbek
Nurzhan Nogerbek

Reputation: 5246

AJAX update list of object

Can someone help me and say whats wrong I did?

In my django project I have product_detail page which has comment part. I am tring to update comments list after successfully adding new comment with AJAX. Unfortunatly it updates all page. I am little bit comfused and need advice. I need to update only list of comments not all page.

product_detail.html:

<div class="card">
   <div class="card-block">
      <table id="comment-table">
         <thead>
            <tr>
               <th>Author</th>
               <th>Date</th>
               <th>Comment Text</th>
            </tr>
         </thead>
         <tbody>
            {% include 'project/comment_list.html' %}
         </tbody>
      </table>
   </div>

   <div class="card-footer">
   <form method="post" class="comment-form" id="comment-form" action="{% url 'project:comment_add' project_code=project.code product_code=product.code %}">
      {% csrf_token %}
         {% for field in form %}
         <div class="form-group{% if field.errors %} has-error{% endif %}">
            {% render_field field class="form-control" %}
            {% for error in field.errors %}
                 <p class="help-block">{{ error }}</p>
            {% endfor %}
         </div>
         {% endfor %}
         <button type="submit" class="btn btn-primary">Send</button>
      </form>
   </div>
</div>

views.py:

def comment_add(request, project_code, product_code):
    data = dict()
    project = get_object_or_404(Project, pk=project_code, status='open')
    product = get_object_or_404(Product, pk=product_code)
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.author = request.user
            comment.save()
            product.comments.add(comment)
            data['form_is_valid'] = True
            data['html_comment'] = render_to_string('project/comment_list.html', {'product': product})
            form = CommentForm()
        else:
            data['form_is_valid'] = False
    else:
        form = CommentForm()
    context = {'project': project, 'product': product, 'form': form}
    return render(request, 'project/product_detail.html', context)

js:

$(function () {
    var saveForm = function () {
        var form = $(this);
        $.ajax({
            url: form.attr("action"),
            data: form.serialize(),
            type: form.attr("method"),
            dataType: 'json',
            success: function (data) {
                if (data.form_is_valid) {
                    $("#comment-table tbody").html(data.html_comment);
                }
                else {
                    $("#comment-form").html(data.html_comment_form);
                }
            }
        });
        return false;
    };

    $("#comment-form").on("submit", ".comment-form", saveForm);
});

Upvotes: 0

Views: 860

Answers (1)

Christian Carrillo
Christian Carrillo

Reputation: 414

The problem is type="submit" native refresh new page. You have to stop form submitting. Try something like this:

$("#comment-form").submit(function(event) {

      /* stop form from submitting normally */
      event.preventDefault();


     // here your ajax code
});

Upvotes: 1

Related Questions