Reputation: 109
Can anyone give example of how to use CHtml::ajaxbutton
with Yii for posting the elements without form?
Upvotes: 4
Views: 23284
Reputation: 3677
Quick Example
<?php
echo CHtml::ajaxSubmitButton('ButtonName',Yii::app()->createUrl('advert/LoadAdvertFromSay'),
array(
'type'=>'POST',
'data'=> 'js:{"data1": val1, "data2": val2 }',
'success'=>'js:function(string){ alert(string); }'
),array('class'=>'someCssClass',));
?>
You need a data
parameter inside the ajaxoptions
Upvotes: 7
Reputation: 367
More examples of Yii ajax button
echo CHtml::ajaxButton(
$label = 'Click me',
$url = '/',
$ajaxOptions=array (
'type'=>'POST',
'dataType'=>'json',
'success'=>'function(html){ jQuery("#your_id").html(html); }'
),
$htmlOptions=array ()
);
//Output
<a href="#" id="yt0">Click me</a>
<script type="text/script">
jQuery('body').on('click', '#yt0', function () {
jQuery.ajax({
'type': 'POST',
'dataType': 'json',
'success': function (html) {
jQuery("#your_id").html(html);
},
'url': '/',
'cache': false,
'data': jQuery(this).parents("form").serialize()
});
return false;
});
});
</script>
Upvotes: 0
Reputation: 6356
To pass the data, you need to add it to your ajax array, e.g.:
<?php
echo CHtml::ajaxSubmitButton('ButtonName',Yii::app()->createUrl('advert/LoadAdvertFromSay'),
array(
'type'=>'POST',
'data'=> 'js:$("#dataContainer").serialize()',
'success'=>'js:function(string){ alert(string); }'
),array('class'=>'someCssClass',));
?>
In this case, all input type elements in the element with id dataContainer
would be submitted, and could be accessed via $_POST.
Obviously, the JS could be more complicated, you could get values from certain elements, and build your own object, e.g.:
'data' => 'js:{"field1": $("#input1").val(), "pageTitle": $("title").text() }'
Then, in your controller, you could access $_POST["field1"]
and $_POST["pageTitle"]
, though I generally tend to access items via CHttpRequest::getParam() as then I can get either POST or GET values, e.g. CHttpRequest::getParam('field1')
Upvotes: 4