Adding To A Shopping Cart Without Redircting The Page



I’m very new to Yii, this group, and web development. However, I’m not new to programming (10 years). By the way, I absolutely love Yii. It’s fantastic.

I’m building a shopping cart using the Yii 1.1.x framework. I downloaded the shopping-cart-component extension library to assist.

On my header page (../views/layouts/main.php), I have a common cart icon which I want to update with the number of items added to the cart. Dynamically.


What I want is that when the user clicks on a ‘buy’ button next to an item in the shopping page, the cart quantity on the page will increment without leaving that page. My problem is that I don’t know how to achieve this. Best I can do now is redirect the page back to where the user was after executing the Model’s action code. Which is not the desired effect.


I have a shopping view page (../views/product/detail.php). That page has a CActiveForm. In that form I added a CHtml::submitButton button. When this button is clicked the action is to call my controller actionAdd() function (/product/add) in a POST manner.


How do I add that item to my cart and update the basket icon’s quantity label without leaving the shopping page? That is, what do I do at the end of my Controller::actionAdd() function?





  $qty = $_POST['quantity'];


  // <img src='' class='bbc_emoticon' alt='???' /> $this->redirect(Yii::app()->request->urlReferrer);

} else {

 // throw new CHttpException('....');



Thanks in advance.


You should call your controller through Ajax. And return back to your view (as as string or json) any information that is needed to update the shopping cart.

There are some wikis over here on using Ajax with Yii.

Thank you. With your help I’ve found some examples and have put together an Ajax call. It’s not looking too elegant at the moment but it’s working. I’ll refactor it when I learn more.

This is what I have so far (for the benefit of others):



CHtml::ajaxButton('Add to basket', 


              array('update' => '#basketItemCount', // this is the div element's id of the basket qty tag in main.php

                    'data'=>array('id'=>$product->product_id, 'qty'=>'js:function(){return document.getElementById("qty").value}')), // this retrieves the user's qty entry from a textBox element





	 * Add product to cart here


	function actionAddToBasket()


		if(Yii::app()->request->isAjaxRequest) {

			if(isset($_GET["id"]) && isset($_GET["qty"])) {

				$product = Product::model()->findByPk($_GET["id"]);

				if(isset($product)) {


					$this->renderPartial('_basketqty', array('product' => $product));	







   echo Yii::app()->shoppingCart->getItemsCount(); // this is the only entry in this file