Unable to display a Message immediately while adding to wishlist url by clicking the wishlist button from the product card

this is the views.py function for the backend

    from django.http import JsonResponse
    from django.views.decorators.csrf import csrf_exempt
    from django.contrib.auth.decorators import login_required
    from .models import Product, Wishlist

    @csrf_exempt
    @login_required
    def add_to_wishlist(request):
        product_id = request.GET.get('id')
        product = Product.objects.get(id=product_id)

        wishlist_count = Wishlist.objects.filter(product=product, user=request.user).count()

        if wishlist_count > 0:
            msg = "Product already exists in wishlist"
        else:
            Wishlist.objects.create(product=product, user=request.user)
            msg = "Product added to wishlist"

        wishlist_count = Wishlist.objects.filter(user=request.user).count()
        request.session['wishlist_count'] = wishlist_count

        return JsonResponse({"bool": wishlist_count > 0, 'totalwishlistitems': wishlist_count, 'msg':   msg})

this is my functions.js ajax call to sent to the backend

$(document).ready(function () {
    $(document).on('click', '.add-to-wishlist', function (event) {
        event.preventDefault();
        event.stopPropagation();

        console.log('Button clicked');

        let product_id = $(this).data("product-item");
        console.log("Product ID is", product_id);

        let this_val = $(this);

        $.ajax({
            url: "/add-to-wishlist",
            data: { "id": product_id },
            dataType: "json",
            beforeSend: function () {
                console.log('Before sending AJAX');
                this_val.css("color", "red");
            },
            success: function (response) {
                console.log('AJAX success', response);
                this_val.toggleClass("wishlist-added", response.bool);

                $(".wishlist-items-count").text(response.totalwishlistitems);

                if (response.msg) {
                    console.log('Message from server:', response.msg);

                    // Create the message element
                    const message = $('<div class="wishlist-message">' + response.msg + '</div>');
                    console.log('Message element created:', message);

                    // Append the message element to the page
                    $('body').append(message);
                    console.log('Message element appended to body');

                    // Show the message element
                    message.fadeIn();
                    console.log('Message element faded in');

                    // Hide the message element after 3 seconds
                    setTimeout(function () {
                        message.fadeOut(function () {
                            $(this).remove();
                            console.log('Message element removed');
                        });
                    }, 3000);
                } else {
                    console.log('No message received from server');
                }
            },
            error: function (xhr, status, error) {
                console.log('Error in AJAX request', error);
            }
        });
    });
});

this is my index.html heat button to add to the wishlist url

{% for p in products %}
<div class="col-lg-3 col-md-4 col-sm-6 mix oranges fresh-meat">
    <div class="featured__item">
        <div class="featured__item__pic"
            style="cursor: pointer; background-image: url('{{ p.image.url }}');"
            onclick="redirectToProductDetail('{{ p.id }}')">
            {% if p.get_percentage %}
            <div class="discount-badge">
                {{ p.get_percentage | floatformat:0 }}%
            </div>
            {% endif %}
            <ul class="featured__item__pic__hover">
                <li>
                    <div class="no-redirect-1">
                        <a class="add-to-wishlist" data-product-item="{{ p.id }} "><i class="fa fa-heart"></i></a>
                    </div>
                </li>
                <li>
                    <a class="no-redirect" onclick="shareProduct()"><i class="fa fa-share"></i></a>
                    <div id="shareModal" class="modal">
                        <div class="modal-content">
                            <h2>Share this product</h2>
                            <div class="share-icons">
                                <a href="https://www.messenger.com/" target="_blank" class="share-icon">
                                    <i class="fab fa-facebook-messenger"></i> Messenger
                                </a>
                                <a href="https://www.instagram.com/" target="_blank" class="share-icon">
                                    <i class="fab fa-instagram"></i> Instagram
                                </a>
                                <!-- Add more share options as needed -->
                            </div>
                        </div>
                    </div>
                </li>
                <li>
                    <div class="add-cart">
                        <input type="hidden" class="product-quantity-{{ p.id }}" value="1" id="product-quantity">
                        <input type="hidden" class="product-pid-{{ p.id }}" value="{{ p.pid }}">
                        <input type="hidden" class="product-image-{{ p.id }}" value="{{ p.image.url }}">
                        <input type="hidden" class="product-id-{{ p.id }}" value="{{ p.id }}">
                        <input type="hidden" class="product-title-{{ p.id }}" value="{{ p.title }}">
                        <a class="no-redirect add-to-cart-btn" data-index="{{ p.id }}">
                            <i class="fa fa-shopping-cart"></i>
                        </a>
                    </div>
                </li>
            </ul>
        </div>
        <div class="featured__item__text">
            <span class="text-muted">{{ p.category }}</span>
            <h6><a href="{% url 'core:product_detail' p.pid %}">{{ p.title }}</a></h6>
            <div class="d-flex">
                <h6>⭐⭐⭐⭐⭐</h6>
                <h6>(5.0)</h6>
            </div>
            <h6 class="">By <a href="{% url 'core:vendor_detail' p.vendor.vid %}"><span
                        class="text-success">{{ p.vendor.title }}</span></a></h6>
            <div class="d-flex justify-content-between align-items-center mt-2">
                <div class="d-flex">
                    <h5 class="new-price current-product-price-{{p.id}}" value="{{ p.price }}"
                        id="current-product-price">{{ p.price }}</h5>
                    {% if p.old_price > 0 %}
                    <h5 class="old-price mx-3 text-muted" style="text-align: left;"><del>${{ p.old_price }}</del></h5>
                    {% else %}
                    <div></div>
                    {% endif %}
                </div>
                <div class="actions">
                    <input type="hidden" value="1" min="1" style="width: 50px;" id="product-quantity"
                        class="product-quantity-{{p.id}}">
                    <input type="hidden" value="{{ p.pid }}" class="product-pid-{{p.id}}">
                    <input type="hidden" value="{{ p.image.url}}" class="product-image-{{p.id}}" style="width: 50px;">
                    <input type="hidden" value="{{ p.id }}" class="product-id-{{p.id}}" style="width: 50px;">
                    <input type="hidden" value="{{ p.title }}" class="product-title-{{p.id}}">
                    <button class="btn btn-success add-to-cart-btn" id="add-to-cart-btn" data-index="{{ p.id }}">
                        <i class="fa fa-shopping-cart"></i> Add
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>
{% endfor %}

When using messages.success("Product has been added to wishlist") in Django, the success message is added to the session and displayed on the next page load. This approach requires a page refresh for the message to appear, which is why you’re only seeing it after reloading the page.

New contributor

Sandesh Ranabhat is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật