An Expert Guide On How To Use AJAX With Yii 1.1

Use AJAX With Yii 1.1

Ajax is powerful JavaScript-based technology which enables a website to dynamically fetch data and show data without refreshing page. This will provide more speed up the website and great user experience.

== Here is two basic method of use of AJAX ==

1. Use AJAX script into js file.

2. Use AJAX script into view file.

 

1. Use AJAX script into js file:

=> First you need to registering js file. You need to register your js file to your application where from all script are loaded. For example (protected/views/app/index.php).
 

Example:

<?php
/* @var $this AppController */
 
// Include the client scripts
//Site base url
$baseUrl = Yii::app()->baseUrl;
 
$clientScript = Yii::app()->getClientScript();
$clientScript->registerScriptFile($baseUrl.'/js/myAjaxScript.js');
?>

 

=> Now you have to handle action into a controller that will be called by JS file. And provide an appropriate response to the JS file.

Example:

file:- AppController.php

<?php
    public function actionMyAjaxFun(){
   	 $call = $_POST['ajaxData'];

   	 // output some JSON Data
   	 header('Content-Type: application/json; charset="UTF-8"');

   	 //Encode response data into JSON format.
   	 echo CJSON::encode(array('output'=>$response));
    }
?>

 

=> Your ajax function that is used for process ajax call and provides a response if there is no error.

Example:

file:- myAjaxScript.js

ajaxCall = function(call){
        	jQuery.ajax({
            	// The url must be appropriate for your configuration;
            	// this works with the default config of 1.1.11
            	url: 'index.php?r=app/myAjaxFun',
            	type: "POST",
            	data: {ajaxData: call},  
            	error: function(){
             	   alert('error');
         	   	},
            	success: function(resp){
                	   nextThingToDo(resp);  // deal with response
                	}
            	});
        	};

 

Note: URL configuration of application will correct for working with Ajax. So prefer (1) provide js variable from view file, (2) Use js into view file.

 

2. Use AJAX script into view file:

=> You need to add ajax script into view file. For adding script into view you need to use Yii::app()->clientScript->registerScript(id, script) function.

Here is an example of load city on the basis of a selected state by ajax.

Example:

I) In View file:

Yii::app()->clientScript->registerScript('stateform','  $("#state").live("change",function(){   
      $.ajax({
   	url: '".Yii::app()->createAbsoluteUrl("site/stateByCity")."',
   	type: "POST",      	 
   	data: "cityid="+$("#City_id option:selected").val(),
   	dataType: "json",
   	"success": function(data){          	 
         	     if(data==null){
              	$("#city").empty();   
         	     }
                else{
              	var obj = eval(data);
              	$("#city").empty();
              	$.each(obj, function(key, value) {
                 	$("#city").append("<option value="+key+">"+value+"</option>");
              	});
                 }
        	 }
       });
    });
 ');
 ?>
    
    <div class="row">
   	 <?php echo $form->labelEx($model,'state'); ?>
   	 <?php echo $form->dropDownList($model,'state',$stateList); ?>
   	 <?php echo $form->error($model,'state'); ?>
    </div>
    
    <div class="row">
   	 <?php echo $form->labelEx($model,'city'); ?>
   	 <?php echo $form->dropDownList($model,'city',
   	                             	array(''=>'Select City')); ?>
   	 <?php echo $form->error($model,'city'); ?>
    </div>

 

II) In Controller file:
 

public function stateByCity() {
      if(Yii::app()->request->isPostRequest) {
    	if(isset($_POST['cityid']) && $_POST['cityid']!=''){
       	$cityModel=City::model()->findAll(array('condition'=>'isactive=1 and city_id='.$_POST['cityid'],'order'=>'name'));
       	if($cityModel){
          	$data=CHtml::listData($cityModel,'cityid','name');
          	print_r(json_encode($data));
        	}
    	}
      }
      else
   	throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
    }

 

I hope these examples help you to understand the basics of Ajax in Yii. Need more assistance regarding Yii Development Service Contact Us now!