Home > Net >  How to update the content of a div after an AJAX call
How to update the content of a div after an AJAX call

Time:11-30

I have a div (<div >) and I want to put elements inside from the database (the elements are retrieved via AJAX call)

But I need something dynamic since I will be adding content dynamically and apparently Django template tags are not enough.

How can I do something like that from the ajax success function?

index.html:

{% extends 'base_generic.html' %}
{% load static %}
{% block content %}
{% get_current_language as LANGUAGE_CODE %}
<script type="text/javascript">
    $(document).ready(function () {
        $.ajax({
            url: '/todo_ajax/',
            type: 'get',
            success: function(data) {
                alert(data);
            },
            failure: function(data) { 
                console.log('Got an error dude');
            }
        });
    });
</script>
<div class="wrapper">
    <!-- Index Content  -->
    <div id="content">
        <div class="row row-cols-1 row-cols-md-3 g-4 mb-5">
            <div class="col">
                <div class="card h-100">
                    <div class="card-header" id="toDoHeader">
                        ... (truncated)
                    </div>
                    <div class="card-body">
                        {% for o in some_list %}
                        <div class="cardItem cardItemIndex" class="mb-3">
                            <div class="row">
                                <div class="col">
                                    <h6 class="card-title">{{ o.title }}</h6>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col">
                                    <p class="card-text">{{ o.description }}</p>
                                </div>
                            </div>
                            <p class="card-text to-do-footer">{{ o.start_date }} - {{ o.end_date }}</p>
                        </div>
                        {% endfor %}
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

views.py

@login_required
def todo_ajax(request):
    response = dict()
    if request.method == 'GET':
        to_do_list = ToDoList.objects.all().filter(user=request.user)
        data = serialize("json", to_do_list)
        return HttpResponse(data, content_type="application/json")
    return HttpResponse('')

models.py

from django.db import models
from django.contrib.auth.models import User

class ToDoList(models.Model):
    title = models.CharField(max_length=60)
    description = models.TextField()
    start_date = models.DateTimeField(null=True)
    end_date = models.DateTimeField(null=True)
    user = models.ForeignKey(
        User,
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
    )

In other words, how can I 'create' this part dynamically when the AJAX function is called:

<div class="card-body">
    {% for o in some_list %}
    <div class="cardItem cardItemIndex" class="mb-3">
        <div class="row">
            <div class="col">
                <h6 class="card-title">{{ o.title }}</h6>
            </div>
        </div>
        <div class="row">
            <div class="col">
                <p class="card-text">{{ o.description }}</p>
            </div>
        </div>
        <p class="card-text to-do-footer">{{ o.start_date }} - {{ o.end_date }}</p>
    </div>
    {% endfor %}
</div>

CodePudding user response:

The dynamic part needs to be done with javascript.

Make a function that can generate cards, and call that after you parse the output as JSON

<script>
var cardItem = function(o) { 
    return `
    <div  >
        <div >
            <div >
                <h6 >`   o.title   `</h6>
            </div>
        </div>
        <div >
            <div >
                <p >`   o.description   `</p>
            </div>
        </div>
        <p >`   o.start_date   ` - `   o.end_date   `</p>
    </div>
    `;
}

    $(document).ready(function () {
        $.ajax({
            url: '/todo_ajax/',
            type: 'get',
            success: function(data) {
                data = JSON.parse(data);
                var cardItems = '';
                for(var i = 0; i < data.length; i  ) {
                    cardItems  = cardItem(data[i]);
                }
                $("#targetDiv").html('<div >'   cardItems   '</div>');
            },
            failure: function(data) { 
                console.log('Got an error dude');
            }
        });
    });
</script>

<div id="targetDiv"></div>
  • Related