i am new to php,jquery and to programming itself.I have a model called Appoinments .I am calling an ajax query from a text field to a controller action 'appoinments/loaddates'.The ajax query executed correctly. But from the ajax action i want to get some array of variables to the view.Can somebody help me please how to do it?
my view
echo CHtml::activehiddenField($model,'doctor',array(
'onchange'=>CHtml::ajax(array(
'type'=>'POST',
'url'=> CController::createUrl('loadDates'),
'update'=>'#nick_result',
'dataType'=>'json' ,
'select'=>"js:function(event, ui) {
$('#nick_result').val(ui.item.x);
}"
))
));
<div id="nick_result">
</div>
my controller
$arr[] = array(
'x'=>$x, //this I need in view
'y'=>$y,
'z'=>$z,
'p'=>$q,
);
echo CJSON::encode($arr);
how to get the $x value as a variable in php as it is used by the datepicker in my form. Any help appreciated.One thing to notice is that I just need a variable to get updated, not a model attribute. I just want to get that outside of the javascript. Thanks in advance.
To achieve this you need to use ajax callback in your view. For example:
echo CHtml::activehiddenField($model, 'doctor', array(
'onchange'=>CHtml::ajax(array(
'type'=>'POST',
'url'=> CController::createUrl('loadDates'),
'update'=>'#nick_result',
'dataType'=>'json',
'select'=>"js:function(event, ui) { $('#nick_result').val(ui.item.x); }"
'success'=>'js:function(data){
//do here what you want to do. Your json encoded array will be passed as data
}'
))
));
I recommend to use firebug for this, in console you can see what you send to ajax action in your post/get and your ajax callback (data).
Related
Please, explain to me how to run snippet CookieList with ajax?
I tried next:
1. Created snippet ajaxCookieList:
<?php
if (isset($_POST["action"])) {
$values = $modx->runSnippet('addToCookieLIst',array(
'value' => $_POST['action']
));
$output = $modx->runSnippet('pdoResources',[
'parents' => 6,
'resources' => $values,
'tpl' => 'popup.favorites.item',
'includeTVs' => 'header.bgImage,franchise.logo,franchise.price,title,subtitle',
'prepareTVs' => '1',
'hideContainers' => '1'
]);
return $output;
}
Then i created chunk with this code:
<script>
jQuery(function($){
$('a.franchise-pin, a.franchise-favorite-add').click(function(e){
var value = $(this).data('value');
$.post(document.location.href, {action: value}, function(data) {
$('#favorites').html(data);
$('#favorites').modal('show');
});
e.preventDefault();
});
});
</script>
But response is all page..
What is wrong?
What I usually do in such cases:
I place a snippet call ([[!ajaxCookieList]]) on a service page
accessible via URL like /page-with-snippet/
In JS (ajax) I use that URL to which I send parameters
The snippet has to get the parameters I send. So, I really call it like this: [[!ajaxCookieList? &action=[[!#POST.action]]]]
Access to parameters in snippets is possible like this: $option = $modx->getOption('action', $scriptProperties, 'default_value', true);
I do my stuff in the snippet
But in your case, I think, everything can be simpler. You use one of the pdoTools snippets and if I am not mistaken, you can just place pdoResources snippet call on a page (/page-with-snippet/) like this:
[[pdoResources?
&parents=`6`
&resources=`[[!addToCookieLIst? &value=`[[!#POST.action]]` ]]` // your snippet should return comma-separated list of resources` ids that you pass then to pdoResources
&tpl=`popup.favorites.item`
&includeTVs=`header.bgImage,franchise.logo,franchise.price,title,subtitle`
&prepareTVs=`1`
&hideContainers=`1`
]]
and now you can send parameters to this page (/page-with-snippet/) via AJAX and get the results if there are any. I hope I didn't mess anything - you had better check it again, but you get the idea at least :) BTW, check this article on modx.com that teaches how to write a good snippet.
Also another minor issue: as it has been pointed out here, the use of window.location is preferable to document.location.
Here is another solution I did. I used pdoResources. Hope that you will understand my code and customize it for yourselves.
Create snippet ajaxCookieList
Paste JS-code in your custom.js file
Simple markup for resources. Insert it in the chunk:
Add to wish list
Remove from wish list
Thas all:)
I have a dropdownlist and a textfield.
If the value of dropdownlist is change, I want to call an action in controller and parsing the result to textfield value.
How can I do that?
Here is my View:
echo TbHtml::dropDownList('isr[setting_merit_demerit_id]', $isr['setting_merit_demerit_id'], $this->getMeritList(),
array('class'=>'span4', // 'onchange' => 'generateNumber();',
'ajax' => array(
'type'=>'POST',
'url'=>CController::createUrl('getMeritDemeritStatus'),
// 'success' =>'js:function(result){$("#tes").val(result).change();}', <--- WHAT SHOULD I PUT HERE?
'data' => array('setting_merit_demerit_id' => 'js:this.value'),
)
)
);
echo TbHtml::textField('isr[show_in_reportcard]',$isr['show_in_reportcard'], array('class'=>'span1', 'id'=>'tes'));
Here is my Controller:
function actionGetMeritDemeritStatus(){
$setting_merit_demerit_id = $_POST['setting_merit_demerit_id'];
$model= SettingMeritDemeritM::model()->findByPk($id);
return $model->status;
}
Sorry for my bad english.. thanks
Your first problem is that you are sending an AJAX request and calling a function that just returns a model. You would have to json_encode return value and then echo it. On the receiving end you would have to, in js: success, parse result and then work with that object and assign its properties as values of text fields.
Hope it helps.
I have a little problem with a Controller method AJAX call in Yii. The thing is that I'm trying to filter the data of one dropDownList based in the value of a previous selected item.
In the view file, where I figured out is the source of the problem, I have this piece of code:
<?php echo $form->labelEx($model,'Estado'); ?>
<?php echo $form->dropDownList($model,'estado',CHtml::listData(Estado::model()->findAll(),'id','nombre'),array(
'ajax'=>array(
'type'=>'POST',
'url'=>CController::createAbsoluteUrl('buscar/select'),
'update'=>'#'.CHtml::activeId($model,'tbl_municipio_id'),
),
'class'=>'form-control'
));
?>
<?php echo $form->error($model,'Estado'); ?>
On the Controller side, I got this:
public function actionSelect(){
echo "Hello world";
$data = Municipio::model()->findAll('tbl_estado_id=:tbl_estado_id',
array(':tbl_estado_id'=>(int) $_POST['Consultorio_estado']));
$data = CHtml::listData($data,'id','name');
foreach($data as $value=>$name)
{
echo CHtml::tag('option',
array('value'=>$value),CHtml::encode($name),true);
}
The ajax call to the Select method isn't triggered when the dropDownList is clicked. I tracked the request using Firebug and no error nor fail message is dropped.
Anyone knows what can I do?.
Thanks in advance.
With my knowledge in Yii 1.1.13, there is no such option for ajax for form->dropDownList, just Chtml::dropDownList does.
Therefore you have option to manually custom event change of form->dropDownList or add more jQuery script to handle it by yourself, or simply switch to use Chtml::dropDownList like below example
<?php
echo CHtml::dropDownList('inst_province','',
array(1=>'A',2=>'B',3=>'C', 4=>'D'),
array(
'prompt'=>'Select City',
'ajax' => array(
'type'=>'POST',
'url'=>CController::createUrl('city/selectAll'),
'update'=>'#city_area',
'data'=>array('city_param'=>'js:this.value'),
)));
?>
http://www.yiiframework.com/wiki/429/an-easy-solution-for-dependent-dropdownlist-using-ajax/
I'm using Yii framework and I want call a PHP function and return a value.
This value has to be appended to a div. I try a lot of things but nothing works. This is more far that I get:
echo CHtml::ajaxSubmitButton('add one more',
CController::createUrl('cadTabelapreco/UpdateFilho'),
array('type'=>'POST',
'data'=>array('item'=>'CadTabelaprecoi',
'i'=>$i,
'complete' => 'function(){
$("#data").append($(this).html());
}',
));
I also try this:
array('type'=>'POST',
'data'=>array('item'=>'CadTabelaprecoi',
'i'=>$i,
'form'=>$form),
'complete' => 'function(ret){
$("#data").append().val(ret);
}',
));
The thing is, if I debug it with Firebug, I see the response and its right, but I can't append the value to the div. How to do that?
echo CHtml::ajaxSubmitButton('add one more',
CController::createUrl('cadTabelapreco/UpdateFilho'),
array('type'=>'POST',
'data'=>array('item'=>'CadTabelaprecoi',
'i'=>$i,
'success' => 'function(data){//pass data to success function
$("#data").empty();//clear div cause if without you'll stack data in your div
$("#data").append(data);//append your url return
}',
));
In your Controller :
public function actionUpdateFilho{
/**
* Do what you need here
*/
echo $result;//form variable string with result wich you want to output(in HTml format wich you need)
}
It's working great for me. Hope this was helpfull.
The problem was the javascript. jQuery's val() returns the value of a input element. If you want to append whatever html or text was returned from the server, the last line should read:
$("#data").append(ret);
I have a dropdown form that with option values 1, 2, and 3. When this form is submitted ($this->Form->create('MyModel', array('action' => 'view'))), I'd like one of these options to be an argument variable that gets passed into the action view and go to controller/view/option_value so that I can load some appropriate data using option_value.
I can't seem to have this option_value passed as the action argument. It's a POST data, so I do have this option_value available to me in the controller, but I thought it would be good to have the value in the URL also because this view.ctp allows the user to update some things and I want the user to be redirected to the referrer easily.
Any ideas? I think this is a client-side issue.. but I'm not yet familiar with Javascripts.
Edit:
Still looking into how to do this.. but for now, I am just redirecting the form-submitted page, which does not include the option_value in the URL, to the same page with the option_value as the parameter. It works for what I need, but if anyone would like to add an answer, I'd appreciate it!
Using jQuery:
<?php
echo $this->Form->create('MyModel', array('id' => 'myForm', 'action' => 'view'));
echo $this->Form->input('MyField', array('id' => 'myField'));
echo $this->Html->scriptStart();
?>
$('#myForm').on('submit', null, null, function(evt) {
var form = $('myForm'),
field = $('#myField');
form.action += "/" + field.value;
form.submit();
evt.stopPropagation();
});
<?php
echo $this->Html->scriptEnd();
echo $this->Form->end(__('Submit', true));
?>
Try that, you might have to tweak some stuff to your needs. Cheers.
-Andrew