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?