Opencart now offers a feature that allows for instant quantity updates in your cart

When using standard opencart functionality, users typically have to manually click the update button after adding a product to their cart in order to update the quantity. To see an example of this behavior, visit . However, I would like the cart information to be updated immediately when I change the quantity. I've attempted to achieve this with the following code:

  1. In catalog/view/theme/default/template/checkout/cart.tpl, I made the following updates:

(I had some trouble pasting the code correctly on the above line. I removed some < characters for clarity)

To implement the update:

<button type="button" data-toggle="tooltip" title="<?php echo $button_update; ?>" class="btn btn-primary" onchange="cart.update('<?php echo $product['key']; ?>', '<?php echo $product['quantity']; ?>');"><i class="fa fa-refresh"></i></button>>
  1. In catalog/view/javascript/common.js

The script contains a function as follows:

var cart = {
  //skipped lines for other functions
    'update': function(key, quantity) {
        $.ajax({
            url: 'index.php?route=checkout/cart/edit',
            type: 'post',
            data: 'key=' + key + '&quantity=' + (typeof(quantity) != 'undefined' ? quantity : 1),
            dataType: 'json',
            beforeSend: function() {
                $('#cart > button').button('loading');
            },
            complete: function() {
                $('#cart > button').button('reset');
            },          
            success: function(json) {
                // Setting a timeout is necessary for updating the total
                setTimeout(function () {
                    $('#cart > button').html('<img src="image/catalog/content/cart/quote-icon.png" alt="quote"><span class="badge badge-giftu rounded-x">' + json['totallines'] + '</span>');
                }, 100);

                if (getURLVar('route') == 'checkout/cart' || getURLVar('route') == 'checkout/checkout') {
                    $('#cart > ul').load('index.php?route=common/cart/info ul li');
                } else {
                    $('#cart > ul').load('index.php?route=common/cart/info ul li');
                }
            }
        });
    },
}

Testing showed that triggering cart.remove under the on.change function worked, but cart.update did not. If anyone knows what may be causing the issue with the ajax update, please advise.

Answer №1

When faced with a similar issue, I approached the solution in the following way

Original code (with custom modifications):

<input type="text" name="quantity[<?php echo $product['key']; ?>]" value="<?php echo $product['quantity']; ?>" size="1" class="form-control"/>
<span class="input-group-btn">
<button type="submit" data-toggle="tooltip" title="<?php echo $button_update; ?>" class="btn btn-primary"><i class="fa fa-refresh"></i></button>
<button type="button" data-toggle="tooltip" title="<?php echo $button_remove; ?>" class="btn btn-danger"
        onclick="cart.remove('<?php echo $product['key']; ?>');"><i class="fa fa-times-circle"></i></button>

New Code (fixed) focusing on input and Remove buttons:

<input type="text" name="quantity[<?php echo $product['cart_id']; ?>]" value="<?php echo $product['quantity']; ?>" 
       size="1" class="form-control"/>
<span class="input-group-btn">
    <button type="submit" data-toggle="tooltip" title="<?php echo $button_update; ?>" 
            class="btn btn-primary"><i class="fa fa-refresh"></i></button>
    <button type="button" data-toggle="tooltip" title="<?php echo $button_remove; ?>" class="btn btn-danger"
            onclick="cart.remove('<?php echo $product['cart_id']; ?>');"><i class="fa fa-times-circle"></i></button>

The issue stemmed from incorrect field notation, which required the use of cart_id instead of key

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

Generate a dynamic chart using Angular-chart.js on a canvas that is created on the fly

I am facing an issue with displaying a chart or table in a div based on an XHR response. In the case of a chart, I want to replace the div contents with a canvas element that will be used by chart.js to show a graph. When I directly include the canvas ele ...

Guide for displaying and hiding an image using a button or link in Next.js

I'm a beginner with React and Next.js, and I have the following code snippet: import Link from 'next/link'; import Image from 'next/image'; async function getPokedex() { const response = await fetch(`http://localhost:3000/api/p ...

Troubleshooting a cross-origin resource sharing problem in Express.js

I've set up Express as the backend for my client application, but I keep encountering an issue when trying to make a request to the GET /urls endpoint. The error message I receive is: Access to fetch at 'http://localhost:5000/urls' from orig ...

Meteor powering the user interface, while Express handles the server-side operations on the backend with NodeJS

When designing a website that requires real-time reactivity like Meteor on the frontend, but also needs a job processing backend (such as Kue), it is clear that the frontend app will benefit from Meteor's capabilities. However, the backend processing ...

Creating a promise to write data to a file

When executing the function, it creates a series of files but fails to write data to them. Strangely, omitting Promise.all at the end and not resolving the function actually results in the data being written to the files. It's puzzling that no matter ...

What is the best way to ensure my arrow text remains properly positioned when using fullpage.js?

Seeking guidance from the web development community. I am currently working on a client's website that utilizes fullpage.js and encountering a persistent issue. On slide1 of the website, I am struggling to display the correct text next to the arrows. ...

What is the best way to bring a list from one .js file into my main.js file?

Here is a demonstration using Ania Kubow's Climate change API. My query is: I have a lengthy list similar to this one, and I would like to store it in a separate file named "exampleList.js" and then import it into my main.js file. const newspapers = ...

Activate dark mode automatically in material-ui

According to the official documentation: The documentation mentions that a dark mode theme will be automatically generated and reflected in the UI, but I am encountering issues with it. Dependencies: "@emotion/styled": "^11.0.0", ...

Cease the progress of a Sequelize promise within an Express.js application

Exploring the realm of promises is a new adventure for me, and I'm still trying to grasp their full potential in certain situations. It's refreshing to see Sequelize now supporting promises, as it greatly enhances the readability of my code. One ...

Challenges with Scope in Using AJAX Calls within an Infowindow

Could it be a scope issue? Feel free to correct me if I'm mistaken. I've got a for loop that's placing markers on my map. Each marker has a different infowindow that loads content using ajax callbacks. This is a simplified version of the s ...

Guide on sending AJAX Request in Yii2 and retrieving JSON

I am facing an issue with my Yii2 web project where I need to return JSON to AJAX. I have tried using json_encode() and Yii::$app->response->format = Response::FORMAT_JSON;, but it doesn't seem to work as expected. Below is the action code: pu ...

Hide a header and bring it back after a 2-second delay

I REPLIED BELOW Is there a way to make the header of my webpage fade out when scrolled and then be hidden using style.display? Here's what I have so far: <script type="text/javascript> function Scroll() { var head = document.getEl ...

How to implement file upload using CodeIgniter and jQuery AJAX

Currently, I am in the process of developing a simple CRUD application using jQuery and AJAX. Here are snippets of the code I've been working on: welcome.php public function add_contestant() { $this->validate(); $path = 'img/'; ...

Trigger file upload window to open upon clicking a div using jQuery

I utilize (CSS 2.1 and jQuery) to customize file inputs. Everything is working well up until now. Check out this example: File Input Demo If you are using Firefox, everything is functioning properly. However, with Chrome, there seems to be an issue se ...

Navigating within a React application using React Router 2.6.0 by triggering a redirection within a click

Currently, I am experiencing an issue while utilizing react-router for constructing a login system with firebase and react. The desired functionality involves redirecting the user to the home page upon successful authentication of their username and passw ...

Iterate through the list elements by utilizing jQuery

I am working with HTML code that looks like this: <ul class="lorem"> <li>text</li> <li>text</li> <li>hello</li> <li>text</li> </ul> Can someone help me figure out how to loop through ...

The occurrence of an error is triggered by the Jquery.ajax()

Here's a useful link for you to try out: If you take a closer look, you'll see that it takes the $_GET['fname'] parameter and outputs the content I need. I made an attempt at solving this: $.ajax({ type: 'GET', url: ...

Prevent collapsing when clicking twice

This section is designed to collapse and expand in its default mode. It will close when the user selects "No" and open/close when the user selects "Yes". I am looking to modify it so that it only closes when the user picks "No" and reopens only when the u ...

Using Vercel for a Next.js Custom Directory Configuration

Seeking guidance on deploying Next.js with Vercel, I have made changes to the structure of my Next.js project: frontend (Current Directory for Next.js) node_modules next.config.js jsconfig.json package-lock.json package.json Contents of package.json scri ...

Circular dependencies in ES6 within a React project

After setting up a test project with React Native, I encountered an issue with circular dependencies being reported by Eslint. Despite this warning, the code still functions properly. This is my package.json configuration: ... "dependencies": { "axio ...