Guide on refreshing a div's content following an AJAX request

I have a container (

<div class="card-body">
) and I want to insert elements from the database dynamically (using AJAX)

However, I require a dynamic solution as I will be adding content on-the-fly and Django template tags alone are not sufficient.

Is there a way to achieve this from within 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('An error occurred');
            }
        });
    });
</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 essence, how can I dynamically generate this portion when the AJAX method is invoked:

<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>

Answer №1

To achieve dynamic functionality, utilize JavaScript.

Develop a function capable of generating cards and invoke it after parsing the output as JSON.

<script>
var createCard = function(data) { 
    return `
    <div class="cardItem cardItemIndex" class="mb-3">
        <div class="row">
            <div class="col">
                <h6 class="card-title">` + data.title + `</h6>
            </div>
        </div>
        <div class="row">
            <div class="col">
                <p class="card-text">` + data.description + `</p>
            </div>
        </div>
        <p class="card-text to-do-footer">` + data.start_date + ` - ` + data.end_date + `</p>
    </div>
    `;
}

$(document).ready(function () {
    $.ajax({
        url: '/todo_ajax/',
        type: 'get',
        success: function(response) {
            var jsonObject = JSON.parse(response);
            var cardItems = '';
            for(var i = 0; i < jsonObject.length; i++) {
                cardItems += createCard(jsonObject[i]);
            }
            $("#targetDiv").html('<div class="card-body">' + cardItems + '</div>');
        },
        failure: function(error) { 
            console.log('An error occurred.');
        }
    });
});
</script>

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

javascript utilizing key inputs

Is there a way I can create a function that activates when the "A" key on my keyboard is pressed, sending a signal to nupp('/TS'), and stops sending the signal when the "A" key is released? <html> <head> <script src=\"htt ...

Utilizing Flask's get and post methods in conjunction with AJAX integration

I am in the process of developing a food calorie web application and would like to extract data from a MongoDB database into an HTML table. This is my python code: from flask import Flask from flask import request import requests from wtforms import Form ...

Securing pages in Laravel and Vue JS: Restricting access to unauthorized users

I have some concerns about my project as it relies on local storage. What if someone figures out how to manipulate it and change roles and permissions set for the logged-in user? For example, if someone changed ['accounting'] to ['accounting ...

What is the process for including icons in Tamagui Input?

I am currently utilizing the Tamagui Input component and I am interested in incorporating icons to enhance its visual appeal. To align buttons with icons alongside my Input component, I have resorted to using a combination of Stacks similar to the followi ...

The submit button remains disabled even after verifying all the required fields

I have a registration form with basic customer details and a Submit button. I have successfully validated all the fields using Ajax, except for the Confirm password field which is being validated using JavaScript. The issue I am facing is that when I val ...

Tips for indicating a method as outdated using swagger_auto_schema?

Currently, I am utilizing swagger-auto-schema to document the API endpoints with django-rest-framework, swagger, and drf-yasg. Is there a method available to indicate deprecated API endpoints within the documentation? ...

AngularJS implementation that disables a button when the input field is empty

As I delve into learning angular JS, I am facing a challenge. I want to disable the button using the "ng-disabled" attribute while my input fields for "login" and "password" are empty. However, the default text in the login input is "LOGIN" and in the pass ...

What methods can be used to assess the security risks posed by a third-party library implemented in a React JS application?

How can I ensure the security of third-party libraries added to my create-react-app with additional scripts? ...

Vue messaging application fails to display data upon mounting

Recently, I've been experimenting with different Vue chat libraries and encountered this interesting piece of code: <template> <p>{{ this.users[0] }}</p> </template> <script> export default { data() { return ...

Implementing a NestJs application on a microcomputer like a Raspberry Pi or equivalent device

I'm facing a challenge in trying to find a solution for what seems like a simple task. I am aware that using the Nest CLI, I can utilize the command "nest build" to generate a dist folder containing the production files of my project. However, when I ...

During the click event, two distinct $.ajax requests interfere and cancel each other out

Here's a dilemma I'm facing: On my webpage, I have implemented two different click events. The first one opens a modal displaying a larger image when you click on a thumbnail picture (similar to Instagram on PC - I created an Instagram clone for ...

Utilizing Namespaces for URLs in Django Registration

Ensuring clean URLs in my project is a priority for me, which is why I utilize namespaces: project/urls.py: urlpatterns = patterns('', url(r'^contracts/', include('apps.contracts.urls', namespace='contracts& ...

What is the best way to create a placeholder for a select option with a looping value?

I have successfully implemented loops for the select options, but I needed to add a placeholder. In other words, I wanted the first value of the select options to be a placeholder, followed by the values generated from the loop. Here is the code that I u ...

What is causing the loss of data when attempting to access an array field within an object?

So I've been grappling with this issue. I have a collection of objects, each containing string arrays and a string based on the following interface: export interface Subscription { uid: string; books: Array<string>; } The problem arises whe ...

Retrieving CSS style values with Node.js

I am looking to design a new CSS style that includes the lowest and highest values. table[my-type="myStyle"] { width: 255.388px !important; } This code snippet is included in numerous CSS files within my style directory. ...

Method for transmitting JSON array from Controller to View using CodeIgniter

I have a function in my controller: function retrieveAllExpenses() { $date=$this->frenchToEnglish_date($this->input->post('date')); $id_user=$this->session->userdata('id_user'); $where=array('date&ap ...

Guide on importing table information into an array using jQuery

I am facing an issue where I want to extract values from a dynamically generated table and then send those values in an AJAX call. The problem is that even though I am able to increase the number of rows in the table dynamically, when I try to capture the ...

Clicking with jQuery to float left and then bringing back

I have written this JavaScript code that is supposed to float the address div to the center when you click on the info panel using the "addressmoved" class. Challenges However, when I click on the trigger button, instead of the address div moving to the ...

Combining Two Collections in Mongoose using Node.js

As a beginner in MEAN Stack, I am currently working on a Node Js application. I have created two collections: var personSchema = Schema({ _id: Number, name: String, age: Number, stories: { type: Array, ref: 'Story' } }); va ...

Different techniques to access values in a JSON array without relying on specific index positions

After making a request to an API, I received a JSON array with various attributes. One of the attributes is "State" and my task is to extract all the "EventName"(s) where State: "PR". The user will select the state from a dropdown menu. In order to achiev ...