Reliable Alternative For Yii::app()->request->isAjaxRequest AND Adding Data To Ajax Form With JS

You are viewing revision #9 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version.

next (#10) »

In this How-To I'll show you:

1.) A reliable alternative to Yii::app()->request->isAjaxRequest (because it doesn't work for everybody and it's not reliable)

2.) How to add extra data to a form without setting a hiddenField, only using javascript, before sending the form.

Here you can read more about why 'isAjaxRequest' isn't reliable:

The main idea is adding a parameter to our request which tells us if the current request is an ajax-request or not. So if you work with an ajax form, you would for example add a hiddenField named 'isAjaxRequest' and set the value to '1'. But this won't work, if you have a form which can be sent with both, ajax- and usual post-request for users having disabled javascript. So the solution is adding a parameter 'isAjaxRequest' to our form with javascript, before sending it, instead of adding a hiddenField.

After building our form, we add a submitButton like this (in this case for searching users):

// Sorry for bad shifting, it's not my fault ...

echo CHtml::ajaxSubmitButton('Search', CHtml::normalizeUrl(array('user/search')), 
                        return false;

jQuery(this).parents("form").serialize() is what Yii's ajaxSubmitButton would usually do, if you had not set the 'data' parameter. Now we add +"&isAjaxRequest=1" to set a parameter 'isAjaxRequest' with value '1' to our ajax-request. So this is how to add parameters to ajax-request with javascript. You can add as many parameters as you want like this. js:jQuery(this).parents("form").serialize()+"&isAjaxRequest=1&parameter1=value1&parameter2=value2"

By setting the parameter 'isAjaxRequest' we can filter our ajax request in our controller-action like follows:

public function actionSearch() {
      if($_POST['isAjaxRequest']=='1') {
        // your business logic for ajax-request
        // usually with renderPartial at the end, in order to render a partial view
        $this->renderPartial('ajaxSearchResult', array('param1'=>'value1'), false, true);
      else {
	 // your business logic for non-ajax-request
         // usually with render at the end, in order to render a whole view with your layout

Very simple, but works ...