Jquery Append + PHP - php

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);

Related

How to run CookieList (MODx extension) with ajax

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:)

ASK:: Parsing function result to textfield using AJAX in Yii

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.

get back a variable from ajax to view

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).

Write the values of the ajaxoptions array dynamically using Yii

I'm calling CHtml::ajaxlink like so:
<?php echo CHtml::ajaxLink('Add to a list',
$this->createUrl('itemList/ajaxadditem'),
array(
'onclick'=>'$("#addToListDialog").dialog("open"); return false;',
'type'=>'POST',
'update'=>'#addToListDialog',
'data' => 'js:{"product_id" : $("#productID").val()}'
),
array('id'=>'showAddToListDialog'));
?>
I don't know how to write the values of the AJAX options array dynamically. I'm using a workaround to get the value using JavaScript, $("#productID").val() and a hidden field.
I want to write something like:
'data' => 'js:{"product_id" : "$model->product_id"}'
But "$model->product_id" is entered as a literal string.
Can anyone give me a way to do this? My method won't actually solve the problem since I need to write this AJAX link multiple times on the fly.
Assuming your $model instance is available, you should be able to append it dynamically like below:
'data' => "js:{'product_id' : '{$model->product_id}'}"

Yii 1.1.3 setting selected value of dependent dropdown part 2

Previously I've created a question where I was wondering how to set selected value for dependent dropdown. That was easy, man adviced me just set second parameter.
echo CHtml::dropDownList('OpenLessons[Building]', $buildingClassID, $buildingList,array(
'ajax' => array(
'type'=>'POST',
'url'=>CController::createUrl('ajax/floorList'),
'update'=>'#OpenLessons_Floor',
)));
echo CHtml::dropDownList('OpenLessons[Floor]',$model->Class_ID, array(),array(
'ajax' => array(
'type'=>'POST', //request type
'url'=>CController::createUrl('ajax/roomList'),
'update'=>'#OpenLessons_Class_ID',
)));
echo CHtml::dropDownList('OpenLessons[Class_ID]',$model->Class_ID, array());
where $buildingClassId is value of select. So that works fine for first select. But how can I set the same for dependent ones? When I look at it's code it looks like this:
<select name="OpenLessons[Floor]" id="OpenLessons_Floor">
</select>
I expected it to have some options, because I set default value for first one. So even if I put as second parameter of seconddropdown some value it wouln't be selected.
Any advices/suggestions?
UPDATE I'd mention that I don't see at XHR console call of floorlist. How can I make it?
UPDATE
$(document).ready(function()
{
$('#OpenLessons_Building').trigger('change');
$('#OpenLessons_Building option').trigger('click');
}).on('change','#OpenLessons_Building',function()
{
console.log('changed');
}).on('click','#OpenLessons_Building option',function()
{
console.log('clicked');
});
Tried like this. Both actions - change and click has happened because I can see output in console, but the dependent arrays are still empty.
You should use $("#OpenLessions_Building").on("change", function() { your code here });
The trigger function was actually does is execute the action (change or click in your case) of the dropdown as soon as the page loads.

Categories