Yii popup confirmation - php

I'm trying my best to alter the below code so that it produces a popup box with a warning and asking for confirmation.
echo CHtml::ajaxButton(Yii::t('mc', 'Wipe Server'), '', array(
'type'=>'POST', 'data'=>array('ajax'=>'wipe', Yii::app()->request->csrfTokenName=>Yii::app()->request->csrfToken,),
'success'=>'function(e) {if (e) alert(e);}'
),
I expect adding 'confirm' => 'Wipe your server?' to add a dialog box but I'm not having much success.
I have this in ServerController:
case 'wipe':
if (Yii::app()->user->can($id, 'wipe'))
{
if (!McBridge::get()->serverCmd($id, 'run:builtin:script wipe'))
echo McBridge::get()->lastError();
}
break;
I would be grateful if anyone can point out where I am going wrong or generally point me in the right direction.
Thank you

Try this one
In Yii ajax button, beforesend function is there. Use that.
Example
<?php
echo CHtml::ajaxButton(
'Submit',
array('controlleraction'),
array(
'success' => 'js:
function (data){
}
',
'type' => 'POST',
'beforeSend' => 'js:
function(){
var r = confirm("Are you sure?");
if(!r){return false;}
}
',
));
?>

Related

ajax not posting, always a blank post

I'm going nuts with this. I am requesting ajax call in several places, and none of these ajax calls are working correctly lately. Today I decided to start fresh on a new section with ajax call. It's the same thing with all the other ones. It's been days that ajax data is not posting to controller - always blank.
Here is one of them. I am trying to allow users to vote up/down on click on CButtonColumn {up}{down}. This view grid "_vote.php" is generated through renderPartial using TbTabs. On renderpartial I did set to true on the last param.
Okay, next the grid. Here it is:
<?php $this->widget('bootstrap.widgets.TbGridView', array(
'type'=>'condensed',
'id'=>'vote',
'dataProvider'=>$dataProvider,
'template'=>"{items}",
'ajaxUpdate'=>true,
'columns'=>array(
array(
'class'=>'CButtonColumn',
'template' => '{up} {down}',
'buttons' => array(
'up' => array(
'label'=>'<i class="fa fa-thumbs-up"></i>',
'imageUrl'=>false,
'url'=>'Yii::app()->createUrl("prod/votecommentup", array("id"=>$data->primaryKey))',
'click'=>' function(){
$.fn.yiiGridView.update("vote", {
type:"POST",
url:$(this).attr("href"),
success:function(data) {
$.fn.yiiGridView.update(vote);
}
}',
),
'down'=> array(
'label'=>'<i class="fa fa-thumbs-down"></i>',
'imageUrl'=>false,
'url'=>'Yii::app()->createUrl("prod/votecommentdown", array("id"=>$data->primaryKey))',
'click'=>' function(){
$.fn.yiiGridView.update("vote", {
type:"POST",
url:$(this).attr("href"),
success:function(data) {
$.fn.yiiGridView.update(vote);
}
}',
),
),
),
),
)); ?>
Okay... next, the url "prod/votecommentup", which is the nearly identical as votecommentdown. Here it is:
public function actionVoteCommentUp($id){
$model = $this->loadModel($id);
if(isset($_POST['VoteThis']))
{
$model->attributes=$_POST['VoteThis'];
$model->prototype_review_id = $id;
$model->user_id = Yii::app()->user->user_id;
$model->vote = "Y";
echo CJSON::encode(array('status'=>'saved'));
}echo CJSON::encode(array('status'=>'not post')); //always give me a no post
}
I recommend testing your calls through something like Postman App for chrome. This will give you the ability to debug your API/AJAX calls independent of your view. Once you have ensured the API/AJAX is functioning correctly, you can then integrate it into the view. This allows you to decouple the debugging process and hopefully make things more transparent as to what is functional and what is not.

update yii listview onchange of dropdown

I want to change pagesize of listview using dropdown. please help me to find solution.
I have read many article but not able to do this. can u find where I'm making mistake
I'm using following code.
code for index.php (view)
code for dropdownlist
<?php echo CHtml::beginForm(); ?>
<?php echo CHtml::dropDownList('CategoryMst_pagesize','20',
array('10'=>'10','20'=>'20','50'=>'50','100'=>'100'
),
array('class'=>'form-control',
/*'ajax'=>array(
'type'=>'GET',
'data'=>array('pagesize'=>'js:this.value'),
'ajaxUpdate':()
),*/
));
?>
<?php echo CHtml::endForm(); ?>
code for listview
<?php $this->widget('zii.widgets.CListView',array(
'id'=>'category_list',
'dataProvider'=>$dataProvider,
'itemView'=>'_view',
'summaryText'=>'{start} - {end} of {count} results',
));
?>
<?php
Yii::app()->clientScript->registerScript('category_update',
"$('#CategoryMst_pagesize').change(function(){
$.fn.yiiListView.update('category_list', {
data: $(this).serialize(),
}
);
});
return false;",
CClientScript::POS_READY);
?>
code in cotroller
public function actionIndex($pagesize=20)
{
$dataProvider=new CActiveDataProvider('CategoryMst',array(
'criteria'=>array(
),
'pagination'=>array(
'pageSize'=>$pagesize,
),
));
$this->render('index',array('dataProvider'=>$dataProvider));
}
You really should not be using $('#CategoryMst_pagesize').change use https://api.jquery.com/on/ instead.
Then from what I see you are not remembering the page size anywhere, after you change it 1 time, as soon as you go to another page it will revert back to what you had before. THis is how I do it:
1) First use something to remember the page size, because right now you do not. I personally recommend this one http://www.yiiframework.com/extension/esaverelatedbehavior/ as it is really, really, really good. It also remember your filters (priceless).
2) create a function for your controller that will just save the page size.
/**
* Saves the new page size for this particular model
*/
public function actionPageSize($pagesize)
{
\Yii::app()->user->setState($this->modelName() . '_pagesize', $pagesize);
}
3) create the dropdown for the pagesize, I use Select 2 but you can use a normal dropdown. same Idea
<?php $this->widget('MySelect2', array(
'name' => 'pageSize',
'data'=>array('10' => '10', '25' => '25', '50' => '50', '100' => '100'),
'options'=>array('allowClear' => false, 'minimumResultsForSearch' => 30),
'htmlOptions' => array(
'data-ajax-dropdown' => $this->createUrl('pageSize'),
'style' => 'width: 80px',
'options'=>array(
(Yii::app()->user->getState($this->modelName() . '_pagesize', Yii::app()->params['defaultPageSize']))=>array('selected'=>'selected')
))));?>
4) I autosubmit the dropdowns for the page size like you do, but I submit them to the function above not to the index page
/*==========================
AUTOSUBMIT DROPDOWNS FOR THE PAGE SIZE
==========================*/
$('#pageSize').live('change',function(e){
var element = $(this);
jQuery.ajax({
"type": "GET",
"url": $(this).attr("data-ajax-dropdown"),
"cache": false,
"data":{pagesize: $(this).val()}
})
.success(function ( response ) {
$.fn.yiiGridView.update(element.closest('.widget.table').find('div.grid-view').attr('id'));
$.jGrowl("Pagination changed", { life: 2000 });
});
});
PS: I know I should not use .live
5) In the search for the model just like you do I have
return new \CActiveDataProvider($this, array(
'criteria'=>$criteria,
'sort'=>array(
'defaultOrder'=>$this->getTableAlias(false,false) . '.name asc',
),
'pagination'=>array(
'pageSize'=> \Yii::app()->user->getState(get_class($this) . '_pagesize', \Yii::app()->params['defaultPageSize']),
),
));

Appending text to CJuiDialog widget dynamically - Yii Framework

I am trying to append text to CJuiDialog widget in Js code, In CJuiDialog content i have two buttons ,
Dialog Widget code,
<?php
$this->beginWidget('zii.Widgets.jui.CJuiDialog',array(
'id'=>'update_tasks',
'options'=>array(
'title'=>'Create Tasks',
'autoOpen'=>false,
'modal'=>false,
'width'=>500,
'height'=>300,
),
));
?>
<table cellspacing="20">
<tr>
<td><?php echo CHtml::button('Add to Current Pending Tasks',array('id'=>'AddPendingTasks'));?></td><td style = "width : 20px"></td>
<td><?php echo CHtml::button('Add to Tasks',array('id'=>'AddTasks'));?></td>
</tr>
</table>
<?php $this->endWidget();?>
Am opening this dialog inside JS code on another button action,
$('.updatetask_btn').click(function(){
var filterid = $(this).closest('tr').find('select')[0].options[$(this).closest('tr').find('select')[0].selectedIndex].value;
var filtername = $(this).closest('tr').find('select')[0].options[$(this).closest('tr').find('select')[0].selectedIndex].text;
document.getElementById('filter-id').value = filterid;
var div = document.getElementById('update_tasks');
div.innerHTML = '<label><b>'+$('#camp-name').val()+' - '+filtername+'</b></label><br>'+div.innerHTML ;
//----- Here am appending text to the dialog dynamically ---
$('#update_tasks').dialog('open');
});
Appending text blocks the two button actions in CjuiDialog content . both button onclick action not working when i append text here. Please give me any idea.
Actually I didn't fully understood your needs but I always do this way:
You need to understand and adapt to your needs.
In main view
Yii::app()->clientScript->scriptMap['jquery.js'] = false;
Yii::app()->clientScript->scriptMap['jquery.min.js'] = false;
Yii::app()->clientScript->scriptMap['jquery-ui.js'] = false;
Yii::app()->clientScript->scriptMap['jquery-ui.min.js'] = false;
....
$this->beginWidget('zii.widgets.jui.CJuiDialog', array(
'id'=>'addot-dialog',
'options'=>array(
'title' => 'Aggiungi OT',
'autoOpen' => false,
'width' => 600,
'height' => 'auto',
'closeOnEscape' => true,
// 'close' => 'js:function() { $("table.items").find("tbody tr div.log-active").removeClass("log-active").addClass("log-inactive"); }'
)
));
$this->endWidget('zii.widgets.jui.CJuiDialog');
?>
.....
$loadurlvendita = Yii::app()->createUrl("/otpos/otVendita/",
array("idot" => $this->idot, "codfis" => $this->codfis));
....
on click here I open and fill let dialog with .load() from another view with render partial
CHtml::link('','',
array('class'=>'be-icon vendita','style'=>'display:block;float:right;padding-right:6px;',
'onClick'=>'$("#venditaot-'.$this->idot.'").dialog("open").load(\''.$loadurlvendita.'\');'
)).
controller
public function actionOtVendita($idot, $codfis) {
$proprietari = Otpos::model()->getOtposProprietari($idot);
$this->renderPartial('vendita', array('idot' => $idot, 'codfis' => $codfis, 'proprietari' => $proprietari), false, true);
}
I hoe it'll help in some way other wise clear better your needs.

Example of calling CakePHP function from jQuery

I am new to CakePHP and I am trying to figure you how to make an asynchronous call from a CakePHP view to a function in the controller. I would like the controller function to return a string and have the view display this string. I would also like to to do this without using helpers. I have been trying to find examples on the web but have been unable to do so. Does anyone have a simple example? I am also using jQuery.
Thanks
CakePHP has a built-in JS Helper to help write aJax functions. The only catch is to include jquery in your head or cake will throw jQuery errors. Heres more information http://book.cakephp.org/2.0/en/core-libraries/helpers/js.html
Your Form:
<?php
echo $this->Form->create('User', array('default'=>false, 'id'=>'YourForm'));
echo $this->Form->input('username');
echo $this->Form->submit('Check Username');
echo $this->Form->end();
?>
The Ajax Function: ('update'=>'#na') is the id of the element you want to update in your view.
<?php
$data = $this->Js->get('#YourForm')->serializeForm(array('isForm' => true, 'inline' => true));
$this->Js->get('#YourForm')->event(
'submit',
$this->Js->request(
array('action' => 'checkUsername', 'controller' => 'user'),
array(
'update' => '#na',
'data' => $data,
'async' => true,
'dataExpression'=>true,
'method' => 'POST'
)
)
);
echo $this->Js->writeBuffer();
?>
The Function in User Controller
function checkUsername(){
$this->autoRender = false;
$username = $this->User->find('first', array('conditions'=>array('User.username'=>$this->request->data['User']['username'])));
if ( $username == true )
echo 'Username is taken';
else
echo 'Username is not taken';
}
EDIT**
*If you want to use jQuery to do this and not the CakePHP Helper you can use aJax to call an action, then update your element like below*
$('#element').on('click', function() {
$.ajax({
url : '/controller/action',
type: 'POST',
success : function(response){
$('#elementToUpdate').html(response);
}
});
}
});
In your Controller Action you can return the "string" you would like to show in the view
function action(){
$string = 'Show this in the view';
return $string;
}
The above example would be executed when you "Click" an element with an id of "element" then upon "Success" would change element with id of "elementToUpdate" to the String "Show this in the view" Since it was returned from the controller action.

Facing Issues With Ajax Update On Page Load

I'm having troubles getting content displayed on page load using ajax. The ajax is calling the right action in the respective controller. The first part of the action code where i update the database is working fine. But the part where i'm calling renderPartial is not working.
**EDIT***
Ok here is the controller action ::
public function actionUpdateProductData() {
Yii::import('application.components.DataScraper.*');
require_once('GetProductData.php');
$productRealTime = RealTime::model()->findAll();
if (count($productRealTime) === 0) {
$symbolData = new GetProductData();
$symbolData->getAmazonProductData();
} else {
echo CJSON::encode( array(
'status' => 'OK',
'div' => $this->renderPartial('_productDataGrid', array(
'model' => $productRealTime),
true, true ),
));
}
}
The if part is working fine. But the else portion is not working.
Here is the view index.php::
<?php
/*
* Include the ajax Stock update script
*
*/
$baseUrl = Yii::app()->baseUrl;
$cs = Yii::app()->getClientScript();
$cs->registerScriptFile($baseUrl . '/js/ajaxProductDataUpdate.js');
?>
<div>
<hr>
<ul class="breadcrumb">
<li>
Home <span class="divider">/</span>
</li>
<li>
Product Info
</li>
</ul>
<hr>
</div>
<div class="span-10">
<div id="section2">
</div>
</div>
Here is the partial view file _productDataGrid.php
<?php
$this->widget('bootstrap.widgets.TbGridView', array(
'id' => 'real-time-grid',
'dataProvider' => $model->search(),
'filter' => $model,
'columns' => array(
'id',
'name',
'category',
'price'
'rating'
array(
'class' => 'bootstrap.widgets.TbButtonColumn',
),
),
));
?>
And here is the jQuery file which is making the ajax request
var productParameters = {
ajaxUpdate: function() {
$.ajax({
url: "/ProductAnalysis/index.php/realTime/updateProductData",
type: "GET",
dataType:"json",
error: function(xhr, tStatus, e) {
if (!xhr) {
alert(" We have an error ");
alert(tStatus + " " + e.message);
} else {
alert("else: " + e.message); // the great unknown
}
},
success: function(data) {
$.fn.yiiGridView.update('real-time-grid', {
data: $(this).serialize()
});
}
});
}
};
$(document).ready(function() {
productParameters.ajaxUpdate();
});
Upon loading the page /realTime/index.php i'm getting an error which says
else:
undefined
Obviously the ajax call is failing, but i don't know how will i fix it. Also in Firebug, the echo date() function in the controller is working, but the Gridview is not working.
Please provide some help on how to solve this. Let me know where i'm doing wrong. I can't seem to make any headway around this.
Thanks in advance,
Maxx
Your actionUpdateStockData() is echoing the date before the actual JSON content is encoded. As a result you're not transmitting correct JSON, and XHR will fail.
Remove the echo date ... line and you should be fine. And as you're just at it - you should add some response for the case where count(RealTime::model()->findAll()) === 0.
Well it seems that the gridview widget won't work with findall(). So i changed the dataprovider to simple model and it works now.
Here is the working code ::
public function actionUpdateStockData() {
Yii::import('application.components.DataScraper.*');
require_once('GetStockData.php');
$productRealTime = new RealTime();
if (count($productRealTime->model()->findAll()) === 0) {
$symbolData = new GetproductData();
$symbolData->getAmazonProductData();
} else {
echo CJSON::encode( array(
'status' => 'success',
'div' => $this->renderPartial('_productDataGrid', array(
'model' => $productRealTime),
true, true ),
));
}
}

Categories