Updating an HTML element in Django using JavaScript and Ajax: A Step-by-Step Guide

I am attempting to modify an html element on a webpage using javascript. Everything works perfectly when the home page initially loads, but when I click on the New Product link, only the context string is displayed on the home page.

html

<!--  product/home.html -->
{% load static %}

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">

        <script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>
        <title>Test context</title>
    </head>
    <body>
    <h1>Test context</h1>
        <div class="container">
            {% block content %}
                Product: <span id="product-code"></span>
                <p><a href="{% url 'new-product' %}">New Product</a><p>
            {% endblock content %}

            <script type="text/javascript" src="{% static 'js/product.js' %}"></script>
        </div>
    </body>
</html>

urls.py

# cardplay/urls.py

from django.urls import path

from .views import HomePageView, NewProduct

urlpatterns = [
    path('', HomePageView.as_view()),
    path('new-product', NewProduct.as_view(), name= 'new-product'), 
]

views.py

# /product/views.py

import random

from django.views.generic import View
from django.shortcuts import render
from django.http import JsonResponse

class HomePageView(View):
    template = 'product/home.html'

    def get(self, request):
        context = {}
        return render(request, self.template, context)

class NewProduct(View):

    def get(self, request):
        code = random.choice(['A123','M456', 'X789'])
        context = {
            'code': code,
        }
        return JsonResponse(context)

product.js

$(document).ready(function () {
    getNewProduct();
});

function getNewProduct() {
    $.ajax(
        {
            type: "GET",
            url: 'new-product',
            cache: false,
            success: function (context) {
                displayNewProduct(context);
            }
        }
    );
}

function displayNewProduct(context) {
    var productCode = document.getElementById('product-code');
    productCode.innerText = context.code;
}

What am I doing incorrectly?

Answer №1

As pointed out by @Swati, I realized I had forgotten to call the function.

product.js

$(document).ready(function () {
    product_link = document.getElementById('product_link')
    product_link.onclick = function(){getNewProduct()};
    getNewProduct();
});
...

html

...
<p><button id="product_link">New Product</button></p>
...

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

Guide on effectively managing props within a single component in React Navigation

When attempting to navigate from my App component to the GamePlay component, I encountered an issue. Here is a snippet of my App.js: import React from 'react'; import { StyleSheet, Text, View, TouchableOpacity } from 'react-native'; imp ...

Please make sure to utilize messageCreate instead of the deprecated message event

Hey there, I'm currently in the process of upgrading my discord bot from v12 to v13. The bot is up and running, all commands are loaded in the console, but I'm facing an issue where a notification keeps popping up at the bottom and none of my com ...

What modifications were implemented in Bootstrap 5 to cause controls to automatically assume their maximum size?

After upgrading NodeJs to version 16.13.0 from 14.x, one of the modules that was updated was bootstrap. This caused me to remove my Jumbotron control due to the upgrade, although I don't believe that is directly related to the issue I am experiencing. ...

Is there a way to set up a local npm module directory without using symlinks

Here is a breakdown of the file structure in a simple way. /my-module ..package.json /my-app ..package.json I am trying to have my-app install my-module locally. This is what I have attempted: "dependencies": { "myModule": "../my-module" } The opti ...

Having trouble with input event listeners in JavaScript?

I've been attempting to trigger the keyup event using EventListener for an input tag, but it doesn't seem to be working and I'm unsure why. Here is the code I have: document.getElementById("ajax").addEventListener("keyup", function() { ...

Replacing text within a paragraph using D3.js

Is it possible to develop a D3 function that can choose a paragraph, delete its content, and replace it with new text? If so, what would be the most effective way to accomplish this? I attempted the following: d3.select("#triggerButton") .on("clic ...

How can you obtain constructor parameter from JSON directly within the constructor itself?

I decided to store the fixed parameters required for creating an object in a JSON file as an array. My goal was to have the constructor of the object fetch these parameters from the file. Although reading a JSON file is efficient, I wanted to explore othe ...

Rearranging components in React does not automatically prompt a re-render of the page

I'm currently working on a project to display the update status of my Heroku apps. The issue I encountered was that the parent component (Herokus) was determining the order, but I wanted them sorted based on their update dates starting from the most r ...

Is it necessary to exclude the 'scripts' folder from your Aurelia project's .gitignore file?

Should I exclude the 'scripts' directory that Aurelia is building to in my CLI project from Git by adding it to .gitignore, or is there a specific purpose for tracking changes to this directory? ...

What is the process for obtaining X through the use of createElement('img')?

Is there a way to retrieve the X position from the left of the tag created using document.createElement('img'); var block00 = document.createElement("img"); block00.src = "images/sep1.png"; If so, how can it be done: if (block00.getBoundingCli ...

Refresh jQuery CSS for active button whenever a different button is clicked

I want to enhance a group of buttons using jQuery. I aim to make the active button visually stand out so that users can easily identify it. These buttons are being created through a PHP foreach loop, as shown below: foreach($result as $row){ echo "< ...

Quasar - Optimize for varied platforms

Currently, I am endeavoring to set up a project with various environments including staging, production, testing, and development. When using Vuejs, this task is quite straightforward. vue-cli-service build --mode staging Additionally, I need to create a ...

Error in Python: The command did not execute successfully as it returned an exit status of 1

Having trouble with this error message: The command '['settings.PDF_TO_TEXT', '-layout', 'absolute_file_path', '-']' returned a non-zero exit status of 1. This is what I am trying to accomplish. def get_qu ...

What steps do I need to take to adjust this function based on the timezone?

Is there a way to retrieve the current time based on a specific timezone of my choice? let getCurrentTime = () => { var today = new Date(); var hh = String(today.getHours()) var mm = String(today.getMinutes()) //January is 0! var ss = ...

Running jQuery scripts through PHP

$("#bt-potrdi").click( function(e) { e.stopPropagation(); $("#belina").css({"z-index":200}); $("body").addClass("ext"); $("#vpisok_frame").css({"z-index":250}).fadeIn(200); }); Upon clicking the button, the ...

Leverage the power of jQuery's .filter() method to pinpoint and target specific text

HTML: <p class="greeting"> hello, my name is kevin. what's yours? </p> jQuery: $("p.greeting").filter(function (){ return $this.text() === "my name is"; }).css("background", "green"); I am attempting to find and highlight the phra ...

How to highlight all the text within a 'pre code block' when double-clicked using JavaScript

Is there a way to make code blocks on my blog automatically selected when double-clicked without using jQuery? Here is the code I have so far: I apologize if this is a silly question, I am still learning! <script type="text/javascript" src="https://c ...

Importing cookies directly into server actions in Next JS 13 is not possible for me

Currently, I am tackling a project using Next JS 13 and came across an issue pertaining to server actions. While server actions can be directly applied on form or button components, my personal preference is to define server components in separate files an ...

Are there any extensions in VS Code that can identify all files that are importing the current file?

class ButtonNoclickTag is exported default {...} I am curious to find out which files have imported this ButtonNoClickTag component through vscode ...

Checked boxes in the React dynamic checkbox list are not being marked

Can you please assist me with the following issue: I am in the process of creating a nested dynamic list of checkboxes for selecting companies and groups within those companies. Upon investigation, I have come up with the following code snippet const [ch ...