Omkar Omkar - 2 months ago 13
PHP Question

Ajax call is not working, "404 not found error" showing in Yii Framework

I've crated simple ajax call function in yii framwork but its not working, its giving 404 not found error message in console.

Ajax function in main.php page


$.ajax({
url: 'actionSendSms',
type: 'GET',
data: {user_id :array_id[i]},
success: function(response){
console.log(response);
}
});


"actionSendSms" in controller:


public function actionSendSms(){
return '1';
}


accessRules() function in controller:


public function accessRules()
{
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('index','view','actionSendSms'),
'users'=>array('*'),
),
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions'=>array('create','update','actionSendSms'),
'users'=>array('@'),
),
array('allow', // allow admin user to perform 'admin' and 'delete' actions
'actions'=>array('admin','delete','actionSendSms'),
'users'=>array('admin'),
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}


The error message from console is:


GET http://www.domain.com/admin/index.php/sendSms/actionSendSms?user_id=32 404 (Not Found)

Answer

You shuld use the call without the "action" prefix

$.ajax({
      url: 'sendSms',
      type: 'GET',
      data: {user_id :array_id[i]},
      success: function(response){                                    
        console.log(response);                                 
      }
    });

accessRules() function in controller:

public function accessRules()
    {
        return array(
            array('allow',  // allow all users to perform 'index' and 'view' actions
                'actions'=>array('index','view','sendSms'),
                'users'=>array('*'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions'=>array('create','update','sendSms'),
                'users'=>array('@'),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions'=>array('admin','delete','sendSms'),
                'users'=>array('admin'),
            ),
            array('deny',  // deny all users
                'users'=>array('*'),
            ),
        );
    }

try echo for response

public function actionSendSms(){
     echo '1';   
  }