How can I implement a seamless add to cart feature in my website using JavaScript and Django, without the need for

Currently, I am working on implementing an add to cart feature and I would like the new cart total to be displayed after adding a product without the need to reload the page. At the moment, the page reloads to show the changes in the cart after a product has been added.

(SOME OF THE CODE MAY BE IN DANISH, HOPE THAT'S OKAY)

HTML (The add to cart button)

<div class="buy-item flex flex-ai-c">
            <button data-product="{{product.id}}" data-action="add" class="add-button add-btn update-cart">TILFØJ TIL KURV</button>
            <div class="flex flex-ai-c flex-jc-c">
                <span class="cart-quantity-text">ANTAL</span>
                <input class="cart-quantity-input" type="number" value="1">
            </div>
        </div>

JS

function addCookieItem(productId, action) {

if(action == 'add'){
    if(cart[productId] == undefined){
        cart[productId] = {'quantity':parseInt(antal.value)}
    }else{
        cart[productId]['quantity'] += parseInt(antal.value)
    }
}

if(action == 'add-from-cart'){
        cart[productId]['quantity'] += 1
}

if(action == 'remove-from-cart'){
    cart[productId]['quantity'] -= 1

    if(cart[productId]['quantity'] <= 0){
        console.log('Remove Item')
        delete cart[productId]
    }
}

if(action == 'delete'){
    delete cart[productId]
}
console.log('Cart:', cart)
document.cookie = 'cart=' + JSON.stringify(cart) + ";domain=;path=/"
location.reload()
}

Django

def cookieCart(request):

try:
    cart = json.loads(request.COOKIES['cart'])
except:
    cart = {}

print('Cart:', cart)
items = []
order = {'get_cart_total':0, 'get_cart_items':0}
cartItems = order['get_cart_items']

for i in cart:
    try:
        cartItems += cart[i]['quantity']

        product = Product.objects.get(id=i)
        total = (product.price * cart[i]['quantity'])

        order['get_cart_total'] += total
        order['get_cart_items'] += cart[i]['quantity']

        item = {
            'product':{
                'id':product.id,
                'name':product.name,
                'price':product.price,
                'imageURL': product.imageURL,
                'stripe-price': product.stripe_price_id,
                'description': product.description,
                'vare_nr': product.vare_nr,
            },
            'quantity': cart[i]['quantity'],
            'get_total': total
        }
        items.append(item)

    except:
        pass
return {'cartItems': cartItems, 'order': order, 'items':items}

def cartData(request):

cookieData = cookieCart(request)
cartItems = cookieData['cartItems']
order = cookieData['order']
items = cookieData['items']


return {'cartItems': cartItems, 'order': order, 'items':items}

Answer №1

There are multiple ways to tackle this issue:

  1. One option is to employ an Ajax call (XMLHttpRequest) using pure JavaScript
  2. You could also explore the possibilities of HTMX, a modern and unconventional method for enhancing your templating abilities without having to write additional JS code.
  3. Another approach would involve utilizing a JS Frontend framework or library such as React, Vue, Angular, Svelte, etc...

Of course, there are other approaches available, but I believe that these options will be the primary ones recommended and well-documented solutions for Django.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Comprehending the concept of error and data callbacks in functions

I'm feeling a bit puzzled about how the function(err, data) callback operates. Is the first argument always designated to handle errors? And what happens with the rest of the arguments in a scenario like function(x, y, z, a, b, c)? How exactly does ...

Unending digest loop when using ng-repeat and filter with Angular.js

I have implemented a custom filter in AngularJS that organizes my elements based on date. Here is the HTML code snippet: <table ng-repeat="(index, groupData) in something = (recentTasks | groupBy:dataGroupBy) track by $index"> The custom filter fu ...

Webpack in Vuejs does not have access to the keys defined in dev.env.js file

The framework utilized here is vuejs-webpack, with build and config files located here. No modifications have been made to these files. According to the information on Environment Variables, the keys specified in dev.env.js should be accessible during the ...

Removing a select menu in Discord.js once a selection has been made

Currently in the process of creating a ticket tool that utilizes a select menu for choosing a topic const row = new MessageActionRow() .addComponents( new MessageSelectMenu() .setCustomId(`select_menu`) .setPlac ...

In the realm of React Native, an error arises when attempting to access 'this._nativeModule.isBluetoothEnabled', as the reference to null prevents it from

Recently, I delved into working with react native and attempted to incorporate react-native-bluetooth-classic into my project. The URL for the API overview can be found here. However, I encountered an issue that has me stuck: "TypeError: null is not ...

How can ternary conditional operators be transformed into if statements?

When dealing with minified code like this, f&&!f.error?k.button.b==k.button.c.G?k.button.Q(b,e,f,c,d):k.button.b==k.button.c.o&&k.button.P(b,e,f,c,d):(console.error(f),f=f.error.message||chrome.i18n.getMessage("error_tooltip"),k.button.v(b ...

Modify css backgroundPosition with Jquery dynamically for both left and top offsets

As a beginner programmer and not a native English speaker, I apologize in advance for any coding or language errors. My goal is to create a 'cropping effect' by making a table draggable over an image. When the table is dragged, I want to replace ...

Identifying Whether Angular ng-repeat is Displaying Output or Not

I am trying to display a "No result" message when the search field does not have any matches. The current filter is working fine, but it does not show the message when there are no results. How can I achieve this? <div class="portfolio-list-wrap" ng-co ...

Tips for updating the border color of a div upon clicking it

Currently working on a project using react/typescript and facing an issue with changing the border color and width of a div upon clicking it: <div className="showroom-card " onClick={() => setSelection({ showroom: &ap ...

Interact with SOAP web service using an Angular application

I have experience consuming Restful services in my Angular applications, but recently a client provided me with a different type of web service at this URL: http://123.618.196.10/WCFTicket/Service1.svc?wsdl. Can I integrate this into an Angular app? I am ...

Move to the next input field once the maximum length is reached

Is there a way to automatically shift focus to the next input field once the previous input has reached its character limit? a: <input type="text" maxlength="5" /> b: <input type="text" maxlength="5" /> c: <input type="text" maxlength="5" / ...

Tips for Incorporating the YouTube Iframe API into Your ReactJS Project

While working in React, I am attempting to build a custom YouTube player component that includes a new set of player controls. The YouTube iframe API provides the following code snippet for creating a player instance: var tag = document.createElement(&ap ...

Transfer the data from the For loop to JavaScript

As I develop a survey form through the ASP.NET MVC structure, I encounter a phase where I extract the survey questions from a model to the view. The model I have created is as follows: [NotMapped] public class QuizForService { public int M ...

Node.js functionality for exporting excel files along with database integration

I am currently exploring the world of node.js and its endless possibilities. In the early stages of planning an application project, I envision creating a system that tracks employee task statuses. The admin will have the ability to export Excel sheets co ...

It is imperative that the query data is not undefined. Be certain to provide a value within your query function that is not undefined

I am utilizing a useQuery hook to send a request to a graphql endpoint in my react.js and next.js project. The purpose of this request is to display a list of projects on my website. Upon inspecting the network tab in the Chrome browser, the request appear ...

Use jQuery to extract content from a markup string in order to acquire text

Below is the code snippet I am working with: <span> Some text blalablalalbal<br/><br/> "You are Amazing" <br/><br/> ----What can I do for you?<br/><br/> </span> I would like to hide the first line and custo ...

Is there a way to verify if a React hook can be executed without triggering any console errors?

Is there a way to verify if a React hook can be invoked without generating errors in the console? For example, if I attempt: useEffect(() => { try { useState(); } catch {} }) I still receive this error message: Warning: Do not call Hooks i ...

The interplay of synchronous flow in Javascript amidst asynchronous function calls

Today was dedicated to diving into jquery deferred, promises, and more. The issue I'm facing seems quite straightforward. I have a main function that calls 4 other functions, some of which include asynchronous calls to fetch data from the server. f ...

Having trouble with blockUI compatibility on Internet Explorer 11?

I have encountered an issue with a piece of code that functions correctly in Chrome and FF, but not in ie11. Interestingly enough, when I tested it in ie8, it worked perfectly fine. Has anyone else experienced similar problems with blockUI on ie11? The s ...

Navigate through json objects with multiple dimensions

I am currently working on a C# project and I have encountered a scenario where I need to return a JSON object containing data from 2 different tables (Table and Table1). My question is, how can I iterate through this data in order to copy it into 2 separa ...