I'm new in using Ajax and javascript. I have an HTML page which will show the shopping status from customers. Like the picture below.
I would like to use Ajax and jquery to implement something like when the customer gets more products or put products back, the database will be updated, and the webpage will display immediately without refresh the webpage by using ajax. Also, it will calculate the total price.
And when the new customer comes in or checks out, the new column will be added or removed.
I have google how to use long polling:
test.js
$(document).ready(function(){
pollServer();
});
var url='127.0.0.1:8000/test/'
var isActive = true;
function pollServer()
{
if (isActive)
{
window.setTimeout(function () {
$.ajax({
url: "http://127.0.0.1:8000/test/",
type: "POST",
success: function (result) {
// alert('TTTT');
pollServer();
},
error: function () {
// alert("FFFFFFF");
pollServer();
}});
}, 3000);
}
}
test.html
<div class="container custom-container-width" style="text-align=center;" >
<div class="row gap-buffer" >
{% for customer in Customer %}
<div class="col-sm-3 p-3 gap-buffer colsize " style="background-color:white;box-shadow: 10px 10px 5px grey; " >
<div class="profilesize">
<img src="{{ MEDIA_URL }}/{{customer.uuid}}/{{customer.uuid}}.jpeg" width=192 height=108 >
</div>
<br>
<div>
<div class="table-responsive" >
<table >
<thead class="thead-dark " >
<tr >
<th>Product</th>
<th>Count</th>
<th>Price</th>
<th>Subtotal</th>
</tr>
</thead>
<tbody >
{% for cart in Cart %}
{% if customer.id == cart.customer_id %}
{% for good in Good %}
{% if cart.id == good.cart_id %}
<tr>
<td>{{good.name}}</td>
<td>{{good.count}}</td>
<td>{{good.price}}</td>
<td> XXX</td>
</tr>
{% endif %}
{% endfor %}
{% endif %}
{% endfor %}
</tbody>
</table>
<br>
<P><strong>Total:</strong></P>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
views.py
def test(request):
context_dict = {}
customers = Customer.objects.all()
carts = Cart.objects.all().select_related('customer').order_by('customer_id')
goods = Good.objects.select_related('cart__customer').order_by('cart_id')
context_dict['Cart'] = carts
context_dict['Good'] = goods
context_dict['Customer'] = customers
return render(request, 'test.html', context=context_dict)
I don't know how to combine it without using php. The problem is I don't know how to get objects in Ajax part.
please give me some advice about how to do it. thanks!!