Yii 1.1: How to add ajax-loading indicators


With yii you're able to create ajax requests and updates easily. But most times you always want to show a loading indicatior to your user.

Here's a simple (and good looking) solution for yii. Basically we'll fade out all elements within a div to 80% opacity, while displaying a loading indicator in the background.

The advantage of this solution is, that you don't have to add extra markup to your page.

When performing the ajax request, add the .loading class to your, usually a div, element. And remove it when the request is complete.

You should put the following code in your view file:

 echo CHtml::form();
 echo CHtml::ajaxButton (
   'DoAjaxRequest', //label
    '', // url for request
    array (
    'beforeSend' => 'function(){
    'complete' => 'function(){
 echo CHtml::endForm();?>

The very slim CSS part of this recepie:

div.loading {
    background-color: #eee;
    background-image: url('loading.gif');
    background-position:  center center;
    background-repeat: no-repeat;
    opacity: 1;
div.loading * {
    opacity: .8;


Russian Version

Total 5 comments

#8683 report it
rix.rix. at 2012/06/19 08:14am
Really helpful - thanks!

What I like to do is call a function in my preloaded js file because i'm not really a fan of too much inline javascript.


In js/myapp.js

function preAjax(){console.log('hola');}
#5776 report it
alrissala at 2011/11/11 11:56am
specify width and height to dispaly image

thanks but it worked for me by adding width and height css properties

div.ajaxloading {
    height: 32px; 
    width: 32px;
    background-color: #fff;
    background-image: url('ajaxloader.gif');
    background-position:  center center;
    background-repeat: no-repeat;
    opacity: 1;
div.ajaxloading * {
    opacity: .8;
#4843 report it
el chief at 2011/08/20 09:16pm
$.ajaxStart is better

can show an ajax throbber for every request. you don't have to change your files. use ajaxStop as well

#4776 report it
drumaddict at 2011/08/14 06:02pm

Just what I was looking for!

#1292 report it
chenc at 2009/09/27 03:16am
Thanks but..

I change into:

public function actionClientselect()

    foreach($data as $v)
        echo CHtml::tag('option',

cause the CHtml(71)get out a mistake.. work well now thanks!

Leave a comment

Please to leave your comment.

Write new article
  • Written by: schmunk
  • Updated by: Yang He
  • Category: Tutorials
  • Yii Version: 1.1
  • Votes: +27 / -1
  • Viewed: 58,250 times
  • Created on: Sep 4, 2009
  • Last updated: Jun 30, 2012
  • Tags: AJAX