rix
rix

Reputation: 10632

Send model attributes to Yii controller using ajax

I'm currently using the following code to send an Ajax get request to my controller:

echo CHtml::ajaxLink('clickMe', array('ajax'), array('update'=>'#results'));

This works fine, the controller receives the request and updates the view accordingly.

Now, I want to send in this request attributes of the model, i.e. from model->getAttributes();

How should I do this? Create a JSON object of the attributes and send that with the request?

Upvotes: 0

Views: 3225

Answers (1)

Choo
Choo

Reputation: 233

Just pass 'data' attribute and 'type' if needed:

echo CHtml::ajaxLink('clickMe', array('ajax'), array(
    'update' => '#results'
    'data' => CJSON::encode($model->attributes),
    'type' => 'post',
));

This code just replaces #results contents with json. If you need something different, use 'success' instead of 'update' like this:

echo CHtml::ajaxLink('clickMe', array('ajax'), array(
    'success' => 'function (response) {
            // do everything you need
    }',
    'data' => CJSON::encode($model->attributes),
    'type' => 'post',
));

Take a look at jquery ajax options for more information.

Upvotes: 2

Related Questions