Hi
i was creating ajax based calculator tonight and i just came to below code
i dont know how to save content in controler to Sum values: eg: when user insert 1 and then press ADD button How save 1 in memory with ajax
my code in controller is:
public $operator;
public static $sum;
public function ActionOperation()
{
$count=$_POST['count'];
$operator=$_POST['operator'];
switch ($operator)
{
case 'add':
self::$sum+=$count;
break;
case 'sub':
self::$sum-=$count;
break;
case 'mul':
self::$sum*=$count;
break;
case 'div':
self::$sum/=$count;
break;
case 'minus':
self::$sum*=-1;
break;
default :
break;
}
$response = array('count'=>self::$sum);
echo json_encode($response);
}
in view file i have:
<div class="calcframe">
<?php echo CHtml::textField('data','0');
Yii::app()->clientScript->registerCoreScript('jquery');
?>
<br />
<div id="operations">
<?php echo CHtml::button("+",array("id"=>"add"));
echo CHtml::button("-",array("id"=>"sub"));
echo CHtml::button("*",array("id"=>"mul"));
echo CHtml::button("/",array("id"=>"div"));
echo CHtml::button("-+",array("id"=>"minus"));
echo CHtml::button("=",array("id"=>"result"));
?>
</div>
<div id="numbers">
<?php
for($i=0;$i<=9;$i++)
{
echo CHtml::button($i,array('id'=>'btn-'.$i));
}
?>
</div>
<script type="text/javascript">
$('#operations input').click(function(){
var operator='operator='+$(this).attr('id')+'&count='+$('#data').val();;
$.ajax({
type:'post',
url:"<?php echo $this->createUrl("calc/operation")?>",
data:operator,
dataType: "json",
success: function(response){
alert(response.count);
$('#data').val(response.count);
}
});
//return false;
});
</script>
</div>
this script just handle operators not operand
another question i have :
is my approach correct or would it better to user CFormModel instance ?