Follow on from my last question, I have a django web app which I am trying to use to display data on a HTML page with data from a database using the JsonResponse method. The website allows users to enter the details of a new product. I am trying to design it so that when they enter the details, a Div underneath will automatically update and show the new item that has been entered as well as the existing items in the database. Here is my code:
The index page:
<!DOCTYPE html>
<html>
<body>
<div>
<h2 id="title">Create product</h2>
<input id="name">Name</input>
<br>
<input id="description">Description</input>
<br>
<input id="price">Price</input>
<br>
<button id="add-product">ADD PRODUCT</button>
</div>
<div id="productList">
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
document.getElementById('add-product').onclick = function(){
sendData();
getData();
}
function sendData(){
var order = {
name: document.getElementById('name').value,
description: document.getElementById('description').value,
price: document.getElementById('price').value
};
$.ajax({
type: "POST",
url: 'create/product',
data: order,
success: function(newProduct){
console.log("success"),
$('#name').val(""),
$('#description').val(""),
$('#price').val("")
}
});
};
function getData(){
$.ajax({
url: 'view/product',
dataType: 'json',
type: 'GET',
success: function(data){
$.each(data.prod, function(index, element){
$('body').append($('#productList', {
text: element.name
}));
});
}
});
}
</script>
</html>
The views.py file:
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from products.models import Product
from django.http import HttpResponse, JsonResponse
def index(request):
return render(request, 'index.html')
@csrf_exempt
def createProduct(request):
if request.method == 'POST':
name = request.POST.get('name')
description = request.POST.get('description')
price = request.POST.get('price')
newProduct = Product(
name = name,
description = description,
price = price
)
newProduct.save()
return HttpResponse('')
def viewProduct(request):
if request.method == 'GET':
product_list = Product.objects.all()
products=[]
for prod in product_list:
products.append({"name": prod.name, "description": prod.description, "price": prod.price})
return JsonResponse(products, safe=False)
Now I think the getData() method is working as when I include a console.log message in the success part of the function, it works and prints to the console. However, it does not add the details of the products to the Div as I would like. Thanks in advance for any answers to this.