Refreshing a widget in Yii

Ajax shopping basketYesterday, I wrote an AJAX shopping basket widget which, as I'm sure you can imagine, I wanted to refresh when items are added or deleted.  However, having written the code to display the widget it confused me for a while how I would update the widget through AJAX.  How do you access the widget from a javascript front-end?  You can't have external methods that can be called externally, so how would I re-use the display code?

The Solution

I trawled the net archives for a short while and couldn't find any way of calling a refresh on the widget directly. In fact, the answer I came up with is so simple that it should have seemed obvious straight away! I added an action to my shopping basket controller which calls a view with just the widget embedded and nothing else.  After all, the purpose of a widget is just to display it.   In that way, I call my new "refreshBasket" action using an ajax call.  The returned data is the widget HTML which I inject back into the basket div. In reality, this is included within the Javascript function that handles updates to the basket as follows:- function changeBasket(vitem) { qty=vitem.value; var url=vitem.attributes["url"].value+"?qty="+qty; jQuery.ajax({ 'url': url, 'success': function(data){ basketVisible=jQuery('#shopping-cart-items').is(':visible'); jQuery("#shopping-cart-wrapper").html(data); if (basketVisible) showBasket(); } }); }

How it works

The link calling this routine is embedded within the detailed cart.  In one case this is using an input field so that users can change the quantity The URL for the update is created within Yii and then embedded as an HTM attribute.  This URL is then extracted in the changeBasket routine with the line starting "url="  This url is then used as the AJAX call. On successful completion of the AJAX call, firstly see if the drop down detail of the basket was visible and store true/false. Then inject the returned HTML back into the basket wrapper. If the detailed basket was visible, then redisplay it.

Did you know you can hire me?

I take on projects of all sizes. From Consulting to large Development Projects.

If you're starting a new Yii project and would like some help to get setup and running or you need some help with a particular module or you just need someone to develop the whole dang thing, then just ask ...

Leave a Comment