use of ajax in yii

Hello

i never use ajax But i want to use it .Can any one explain me step by step how to use ajax in yii.

i know the concept of ajax but i don’t know how to implement it .please help me.

Can U give an example of what U want to do by ajax, It will be easier to explain

for example i have a text box in i want to check username already exist or not.

Get an idea from this link -

http://www.yiiframework.com/wiki/48/by-example-chtml#hh1

I think you don’t need to use ajaxlink method to check username already exist or not.

Just follow these steps -

1. In your model -


public function rules() {

	return array(

		  array('username', 'checkUsername')

		  )

}


public function checkUsername($attribute, $params)

{

   if($user = User::model()->exists('Username=:Username',array('Username'=>$this->username)))

   $this->addError($attribute, 'Username already exists!');

}

2. Add this into your form widget in view

Enable the ajax/jquery validation


'enableClientValidation' => true,

'clientOptions' => array(

		'validateOnSubmit' => true,

),

I’m not trying before but surely it will work perfectly…

i know i can do this but i want to use ajax,so i can understand how to use ajax

ok, something like this :

your input field has id="username"

on page:

$(’#username’).on(‘change’, function() {

var username = $(this).val() // getting value of input field


$.ajax({


    url : '<?php echo Yii::app()->createUrl("yourController/checkUsername");?>',


    type : 'post', // method can be either post or get


    data : {'username':username}, // data to be sent to server (key=>value)


    dataType : 'json' // may be ommited


}).done (function (r){  // here you will handle response (if status code = 200)


    if(r.success)   // if success == true


       alert(r.message)  // alert user


    else                 // if not alert user about error


       alert(r.message)  // alert him about errors


}).fail (function (r) { // you will handle other responses (status code != 200)


    if(r.responseText)


       alert(r.responseText); // if you set (on server some custom response)


    else


       alert(r.statusText); // or use status text


})

})

in yourController class

public function actioncheckUsername()

{

$username = Yii::app()->request->getPost('username'); // collect sent data





if($username)


{


     // perform check, something like:


     $users = User::model()->findAll(['condition'=>'username = "'.$username.'"]);


     //searching for all models in user table with same username;





     if(!empty($users))   // if any record is found means username already exists


     {


         echo CJSON::encode([


             'success' => true,


             'message' => 'Username You selected is already in use.' // set some message


         ]);


     } else {  // no records found so it's safe to use this username


         echo CJSON::encode([


             'success' => true,


             'message' => 'Username You selected is unique.' // set some message


         ]);


} else    // param username was not sent throw exception


    hrow new CHttpException(400, 'Username was not sent');

}

Hope this can help you

Hello!

In your view you make a standard AJAX call to a specific ajax action in your controller. I usually have a controller named "AjaxController" for the ajax requests but you can make an action for example named "actionAjaxDoSomething()" in your standard controller.

Once the call is done, fetch the data by POST for example, do the logic, and then you can renderPartial() an especific view created for showing the ajax response content.

An example of my ajax call:




function realizaProceso(valorCaja1, valorCaja2, valorCaja3, valorCaja4, pagecount){

    var parametros = {

            "cityId" : valorCaja1,

            "type" : valorCaja2,

            "limit" : valorCaja3,

            "current" : valorCaja4

    };

    $.ajax({

            data:  parametros,

            //creating the url by Yii url creator to the controler ajaxController and to the action actionEventAjaxPagination()

            url:   "<?php echo Yii::app()->createUrl('ajax/EventAjaxPagination'); ?>",

            type:  'post',

            beforeSend: function () {

                    $("#content").html("Procesando, please wait...");

            },

            success:  function (response) {

                    //The <div> with id="content" will be filled with the view from the renderpartial function in the controller

                    $("#content").html(response);

            }

    });

}



And in my controller:




public function actionEventAjaxPagination() {


        //Fetching the data ...

        $cityId = $_POST['cityId'];

        $type = $_POST['type'];

        $limit = $_POST['limit'];

        $current = $_POST['current'];

        

        //Doing the logic part of the action ...

        $c = new CDbCriteria();

        $c->addCondition("city_id = " . $cityId);

        $c->limit = $limit;

        $c->offset = $current;

        $c->order = 't.start_date asc';

        $data = LiveEventsSearchView::model()->findAll($c);

         

        //Now we renderPartial our ajax view with the data we want to show ...

        $this->renderPartial('indexSearchPagination', array('data' => $data, 'current' => ($current/PAGINATION_ITEM_LIMIT)+1));


        //stop executing the script to avoid the autorender feature in this action ...

        Yii::app()->end();

    }



Hope it helps!