0

I have a template called basket whenever I want to update the product quantity it works fine but the success message doesn't show until I refresh the page

enter image description here

views.py:

def basket_update(request):
basket = Basket(request)
if request.POST.get('action') == 'post':
    book_id = int(request.POST.get('bookid'))
    book_qty = int(request.POST.get('bookqty'))
    basket.update(book=book_id, qty=book_qty)
    messages.success(request,"Basket Has Been Updated")
    basketqty = basket.__len__()
    baskettotal = basket.get_total_price()
    response = JsonResponse({'qty': basketqty, 'subtotal': baskettotal})
    return response

ajax:

  $(document).on('click', '.update-button', function (e) {
    e.preventDefault();
    var book_id = $(this).data('index');
    $.ajax({
      type: 'POST',
      url: '{% url "basket:basket_update" %}',
      data: {
        bookid: $(this).data('index'),
        bookqty: $('#select' + book_id + ' option:selected').text(),
        csrfmiddlewaretoken: "{{csrf_token}}",
        action: 'post'
      },
      success: function (json) {
        document.getElementById("basket-qty").innerHTML = json.qty
        document.getElementById("subtotal").innerHTML = json.subtotal
      },
      error: function (xhr, errmsg, err) {}
    });
  })
almutairi
  • 27
  • 1
  • 7
  • I'd say this will help you! https://stackoverflow.com/questions/28240746/django-how-to-implement-alertpopup-message-after-complete-method-in-view –  May 06 '22 at 15:28
  • You will need to use some AJAX to fetch the messages and display these. For example with a tool like angular, react or vue. Furthermore please *don't* call `.__len__()` explicitly, you should use `len(basket)`... – Willem Van Onsem May 06 '22 at 15:42
  • It seems you call this view using AJAX, what stops you from rendering the success message yourself on the front-end when you receive a response from the server? – Abdul Aziz Barkat May 06 '22 at 15:53
  • @AbdulAzizBarkat I just uploaded the Ajax code for the update – almutairi May 06 '22 at 16:42
  • did you check JavaScript console in browser? It may display some error. I'm not sure if you can use directly `json.qty` - as for me you may get `string` with JSON data which you have to parse to use `json.qty` – furas May 06 '22 at 19:38

0 Answers0