How to add an AJAX cart in the header in OpenCart

I’ve started working on some templates for OpenCart.  Some of these require having a cart in the header area rather than in the left or right column. In this post I’ll tell you, step-by-step, how to do it in, what I believe, is the best, most satisfactory way.

I’m not really a programmer, so I searched the OpenCart forums and found several ways of doing it.  However, they all involved editing the source code of OpenCart, and when I design a template I want it to be easy to install and uninstall and I don’t want to have to alter the source code of the CMS. Finally, after a lot of searching I found a post by peterban which was exactly what I was looking for.  You can read the post here: http://forum.opencart.com/viewtopic.php?f=21&t=14764

I made some slight alterations to peterban’s solution and it seems to work fine, so here’s what you do.

Basically, if you want to display a cart in your  header you can put the following in your header.tpl file:

<div id="cart_in_header">
<?php
$cart_number = $this->cart->countProducts();
if ($cart_number == 1) {echo "1 item in shopping cart";}
else {echo $cart_number." items in shopping cart";}
echo"<br />";
echo "Total: ".$this->currency->format($this->cart->getTotal());
?>
echo"<br />";
<a href="index.php?route=checkout/cart">View Cart</a> |
<a href="index.php?route=checkout/shipping">Checkout</a>
</div>

If you are not using the AJAX add-to-cart function in OpenCart then that is all you need to do. You now have a basic cart in your header that functions perfectly. However, if you want to add the AJAX function to your cart then here’s what you need to do next.  It does involve editing the source code, but you are only adding an extra function to the source, not altering anything that already exists, which I can live with.

In catalog/controller/module/cart.php add the following at the bottom, before the final }:

public function minicart() {
$this->language->load('module/cart');
$this->load->model('tool/seo_url');
if ($this->request->server['REQUEST_METHOD'] == 'POST') {
if (isset($this->request->post['option'])) {
$option = $this->request->post['option'];
} else {
$option = array();
}
$this->cart->add($this->request->post['product_id'], $this->request->post['quantity'], $option);
unset($this->session->data['shipping_methods']);
unset($this->session->data['shipping_method']);
unset($this->session->data['payment_methods']);
unset($this->session->data['payment_method']);
}
$cart_number = $this->cart->countProducts();
if ($cart_number == 1) {$output = '1 item in shopping cart <br />';
} else {$output = $cart_number.' items in shopping cart <br />';}
$output .= 'Total: '.$this->currency->format($this->cart->getTotal()).'<br />';
$output .= '<a href="index.php?route=checkout/cart">View Cart</a> |
<a href="index.php?route=checkout/shipping">Checkout</a>';
$this->response->setOutput($output, $this->config->get('config_compression'));
}

Now that you’ve done that, all that is left to do is call the function when the Add to Cart button is pressed.  You do that by adding the following javascript to your header.tpl file, just under the code for your basic cart.

<script type="text/javascript"><!--
$(document).ready(function () {
$('#add_to_cart').removeAttr('onclick');
$('#add_to_cart').click(function () {
$.ajax({
type: 'post',
url: 'index.php?route=module/cart/minicart',
dataType: 'html',
data: $('#product :input'),
success: function (html) {
$('#cart_in_header').html(html);
},
complete: function () {
var image = $('#image').offset();
var cart  = $('#cart_in_header').offset();
$('#image').before('<img src="' + $('#image').attr('src') + '" id="temp" style="position: absolute; top: ' + image.top + 'px; left: ' + image.left + 'px;" />');
params = {
top : cart.top + 'px',
left : cart.left + 'px',
opacity : 0.0,
width : $('#cart_in_header').width(),
heigth : $('#cart_in_header').height()
};
$('#temp').animate(params, 'slow', false, function () {
$('#temp').remove();
});
}
});
});
});
//--></script>

And that is you sorted.  You now have a basic AJAX shopping cart in your header that doesn’t involve any real editing of the OpenCart source code.  A couple of points:

  1. This basic cart doesn’t work together with the cart module in the right or left column so you must uninstall the cart module in your admin panel.
  2. You will probably need to give the cart_in_header div a width in your stylesheet in order to get that nice effect of the product shrinking as it glides towards the cart e.g. #cart_in_header {width: 150px;}.
This entry was posted in OpenCart Mods. Bookmark the permalink.

15 Responses to How to add an AJAX cart in the header in OpenCart

  1. Steve Allinson says:

    Thanks Craig. Great article, just what I was after. Worked a treat. Thanks for taking the time to share.

  2. vimal says:

    Hi Craig,

    Thanks for this wonderful tutorial. I tried to implement it and everything works fine except that when I try to add the product to the cart, instead of going to the cart section in the header, it goes to the left of the page. You can see it on
    http://www.seagren.se

    Do you have any idea what I have done wrong?

    PS: I just upgraded the site from v1.3.2 to v1.4.9.3. So the products are not adding to the cart. But still the animation is working but in the wrong direction.

    Thanks!
    Vimal.

  3. Craig says:

    Hi Vimal, glad to help.

    You need to give the cart div the ID “cart_in_header” as I have above, that is the ID that the AJAX code uses.

    That should fix things.

  4. vimal says:

    Thanks Craig! That worked perfectly..

  5. Joe says:

    Hey Craig,
    Would this be possible to do using your Cleaner 2 Default template? Possibly under the search bar on the right side. Any help would be appreciated and thank you for sharing your knowledge with all of us.

  6. Sam says:

    Should this work on 1.4.9.3

    I have copied your code exactly as it appears above and the cart updates perfectly however the product image animation is all over the place.

    I don’t have a link as I am testing locally.

  7. Craig says:

    Hi Joe, that’s exactly where I usually put it. You’ll need to wrap both the search box and the cart in the same div, and float that div right. That’s basically it.

    Hi Sam, it does work on 1.4.9.3 – I’ve used it on several recent shops. Rather than block up the comments, please PM me on the Opencart forum – my user name is Chones.

  8. Parikshit says:

    Hi craig,
    Can you tell me how to delete item from cart.

  9. Craig says:

    Hi Parikshit, this doesn’t list the items, just a total – you need to visit the Cart page to delete an item.

  10. George says:

    Just installed. Works great! Thank you so much for sharing.
    Tip: Works flawlessly with 1.4.9.3. Make sure to keep the #image and the other images in your template that are mentioned in the js code. Took me a while to figure out why it didnt work in the beginning, then i noticed i changed the css naming of some of the elements

  11. yelrah says:

    I want an extra blank line above the counter in the cart.php
    I can make it happen in the header.tpl but when i add an item it will jump 1 line up
    so i need to add an in the cart.php part of the code but where should it be because almost every option i can think of results in a parse error :(

  12. Craig says:

    Well, it depends how you are adding the blank line. If you are just using a <br /> then you just add that to the cart.php like this:

    if ($cart_number == 1) {$output = '<br /> 1 item in shopping cart <br /> ';
    } else {$output = '<br />'.$cart_number.' items in shopping cart <br />';}

  13. yelrah says:

    i was stuck at the second part becuase of the numeral on a different line with my solution. Thank you for your very simpel to use mod (and for your quick repsonse) !

  14. Taj says:

    Thanks for this!

    I have successfully implemented this into a product page through the template (rather than the header) and it works perfect!

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>