views:

76

answers:

4

Hello,

I have a shopping cart in Codeigniter in which products are added to the cart using (jQuery) Ajax. In the header of each page it displays the number of contents in the cart using

<?php echo $this->cart->total_items(); ?>

How can I update/refresh this variable when a product is added to the cart, as I am using AJAX to add products to the cart and thus the page isn't being reloaded when products are added. It seems pointless to use AJAX to do asyncronous stuff if I have to reload the page to get the new number of total items from the server.

Many thanks.

A: 

As I understood you, you need something to dynamically update your number of articles ?

You can use jQuery PeriodicalUpdater to update that number "every once in a while" ( point it to a script that returns the current number only, ofc ).

Kemo
+1  A: 

You should be able to do this by making the element containing the Shopping Card Item Count easily addressable by JavaScript, so:

<span id="total_items"><?php echo $this->cart->total_items(); ?></span>

Then, as part of the AJAX Function you perform, have the response contain the revised value for the total items, and then have your function replace the content of this span with that value.

Lucanos
Thanks Lucanos, please see my reply to PiotrLegnica above. I will do this.
Matt
Happy to help. (And somewhat comforting that I was thinking along the same lines as yourself, and Piotr.)
Lucanos
A: 

Don't think about PHP in this case — it's totally irrelevant. What you need to do is modify content of that element client-side. So if you have:

<div id="total_items"><?php /* ... */ ?></div>

Then in your AJAX success handler you should do something like:

$('#total_items').html('new item count');
PiotrLegnica
Ah I see, I was thinking along these lines, I just wasnt sure if this was the correct procedure or not. I actually got it to work doing this, but I wrongly thought the correct way would be to show the updated variable instead. Thanks for the quick reply!
Matt
A: 

First, you can update as many parts of the page as you want when you make a jQuery call. What is the format of the data that is being returned from the call? Lets say you are returning JSON, then the JSON string should include the total. Then in the callback of the AJAX call you can simply update the total count.

Vincent Ramdhanie