intpp / yii-ajax-action
Yii action for ajax methods
1.0.10
2015-08-17 23:08 UTC
Requires
- php: >=5.3.0
Requires (Dev)
- yiisoft/yii: dev-master
README
Usage:
- Create class for ajax actions (ex.: SiteAjaxAction)
namespace your\namespace\here; use intpp\yii\actions\AjaxAction; class SiteAjaxAction extends AjaxAction { /** * @param string $name * @param int $age * @param string $gender * @param array $hobbies */ public function getFormattedInfo($name, $age, $gender = 'male', array $hobbies) { $this->setOutput('result', true); $this->setOutput('text', implode(', ', [ 'Your name is ' . $name, 'age: ' . $age, 'gender: ' . $gender, 'hobbies: ' . implode(', ', $hobbies) ])); } }
- Include in your controller:
public function actions() { return [ // Other included actions 'ajax' => 'your\namespace\here\SiteAjaxAction', ]; }
- Use in your JS applications:
3.1 In your view or layout file set JS variable with url to ajax action, for example:
$ajaxUrl = Yii::app()->createUrl('/site/ajax'); Yii::app()->clientScript->registerScript('ajaxUrl', "var ajaxUrl='{$ajaxUrl}';");
3.2 In your JS application you use that variable for ajax requests, for example:
$(document).on('click', 'a#getInfo', function() { $.ajax({ url: ajaxUrl, data: { method: 'getFormattedInfo', // <---- Name of a function in your AjaxAction class name: 'Vasya', age: 12, hobbies: ['sport', 'dev', 'sex'] // <---- Parameters for the function }, dataType: 'JSON', success: function(response) { if(response.result === true) { alert(response.text); } } }); });
P.S: Other examples in examples directory =)