Show A Loader Gif On Form Submit

I have a form with file uploading, the form uses validateOnSubmit. I put a loader gif on the form with "display: none". I want to show the loader on pressing the submit button after client validation.

I can edit the following passage in the jquery.yiiactiveform.js:


if (!hasError) {

validated = true;

var $button = $form.data('submitObject') || $form.find(':submit:first');

// TODO: if the submission is caused by "change" event, it will not work

if ($button.length) {

$button.click();

} else {  // no submit button in the form

$form.submit();

}

return;

}

But is there a way to do the same without tweaking the source code of the framework?

Firstly give your form an id. This can be achieved in the view like so:


CHtml::beginForm('','post',array('id'=>'myForm'));

Next, in your controller add something like this:


Yii::app()->clientScript->registerScript('myScript', "

    $('#myForm').submit(function() {

        // show the hidden element with id myLoadingImage

        $('#myLoadingImage').show();

    });

");

The code above will insert some javascript at the bottom of your page to handle the submit.

Your loading image should match the id, in this case ‘myLoadingImage’ which might be a wrapper div around your image in the view:


<div id="myLoadingImage">

    <img src="<?php echo Yii::app()->baseUrl; ?>/images/myLoadingImage.gif" alt="" />

</div>

That’s just one way, there are many others.

Thanks for the answer!

2 more questions:

  1. Shouldn’t I add “return true;” at the end of the function so that the default submit behavior is triggered?

  2. In this function we bind the form submit event and yiiactiveform script triggers form.submit() only when there is no submit button in the form. When there is a submit button the script triggers button.click(). I understand that click on the submit buttom triggers form submission anyway, but if there’s no difference why doesn’t yiiactiveform script trigger form.submit() right away?