Yii ajax jquery multiple request just fist one works - php

Many input field and button pairs for ajax request works only for first time. After first request-response other buttons doesn't call ajax function.
There's a data grid list. Each row has a Title field (as input) with a button to call ajax function for updating this field and refresh list.
first time I click on one of the buttons everything works fine, data sends and list refresh with new data. but after this when I click on one of the buttons nothing happens , even function doesn't call.
Where I'm doing mistake?
My ajax function:
$('.titleBtn').click(function(event){
var id = $(this).attr('name');
var title = $('#' + id).attr('value');
var formAction = '".$this->createUrl('article/changeTitle')."';
$.get(formAction,{id:id,title:title},function(result){
$.fn.yiiGridView.update('article-grid');
}
);
event.preventDefault();
});
My grid list:
<?php $form=$this->beginWidget('CActiveForm', array(
'action'=>Yii::app()->createUrl($this->route),
'method'=>'get',
'id'=>'Artform',
)); ?>
<?php $this->widget('bootstrap.widgets.TbGridView', array(
'id'=>'article-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'ID',
array(
'header'=>Yii::t('labels','Title'),
'name'=>'Title',
'type'=>'raw',
'value'=> function($data) use ($model) {
return '<input type="text" id="'.$data->ID.'" value="'.$data->Title.'"><button type="button" name="'.$data->ID.'" class="titleBtn" >Update</button>';
},
),
....
),
)); ?>
//Some buttons irrelevant to this subject for submitting whole list.
<?php $this->endWidget('CActiveForm'); ?>

You could set the event using delegate
$('#Artform').delegate('.titleBtn', 'click', function() {
...
});

You need to add afterAjaxUpdate option to your TbGridView and add js code to invoke after ajax update and set your handlers.

Related

AjaxSubmitButton in Yii framework does not save

after succeeding in not refreshing the page after submission, my ajaxSubmitButton does not save the data. When I click on the button, it removes the content of the input fields but does not save the data. No message is displayed despite the error and success parameters.
In my form submission, the code for submit button is the following
<?php echo CHtml::ajaxSubmitButton(
'Save',
Yii::app()->createUrl('post/viewComment'),
array(
'success'=>'js:function(data){
alert("commentSubmitted");}',
'error'=>'js:function(data){
alert("comment NOT Submitted");}',
)
);
?>
My controller action code is
public function actionViewComment()
{
$post=$this->loadModel();
$comment=$this->newComment($post);
$this->renderPartial('_viewComment',array(
'model'=>$post,
'comment'=>$comment,
));
the viewCommment view, display the _view view to list the comments and at the end display the _form view to make the user input the new comment
the newComment function contains the following
protected function newComment($post)
{
$comment=new Comment;
if(isset($_POST['ajax']) && $_POST['ajax']==='comment-form')
{
echo CActiveForm::validate($comment);
Yii::app()->end();
}
if(isset($_POST['Comment']))
{
$comment->attributes=$_POST['Comment'];
if($post->addComment($comment))
{
if($comment->status==Comment::STATUS_PENDING)
Yii::app()->user->setFlash('commentSubmitted','Thank you for your comment. Your comment will be posted once it is approved.');
$this->refresh();
}
}
return $comment;
}
Actually, I use the blog demo from Yii Framework, I though it was a good starting point to learn Yii Framework.
the home page display list of posts. (it renderPartial _view.php.)
I create the ajax button to be able to list the commments associated with a given post and display an input form for new comment at the bottom of the form.
I added a second button with the "classical submit"
<?php echo CHtml::submitButton($model->isNewRecord ? 'Submit' : 'Save'); ?>
it works but redirect me to the list of the comments, that's what I wanted to avoid;
By using AjaxsubmitButton. When I put my cursor over the classical button or the Ajax button, the link is the same ...../blog/index.php/post/viewComment?id=...
The display is the following
post 1
post 2
comment 1
comment 2
comment 3
Add comment
Input Field
AjaxSubmit Button
post 3
and when I click on the ajaxsubmit button, I have the following
post 1
post 2
comment 1
comment 2
comment 3
Add comment
Input Field
AjaxSubmit Button
Add comment
Input Field
AjaxSubmit Button
post 3
So I got a second form window below the first one. And the comment is not saved.
Thank you in advance for your help
You are processing the data from POST. But you didn't mention in code.
<?php echo CHtml::ajaxSubmitButton(
'Save',
Yii::app()->createUrl('post/viewComment'),
array(
'type'=>'POST',
'dataType'=>'json',
'success'=>'js:function(data){
alert("commentSubmitted");}',
'error'=>'js:function(data){
alert("comment NOT Submitted");}',
)
);
?>

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

jQuery change not triggering after DIV has already been loaded, using CakePHP

When a room_id is selected from the drop down, I use the JS helper to populate the security_deposit and room_rate inputs. The issue is that if I select a room_id, the room_rate_update jQuery change function stops working. However, when page loads and I don't select a room_id, I can type in the room_rate box and it's triggered, but not after I select a room_rate.
The one thing that I think may be causing this is when I select a room_id, the entire div containing the room_rate is updated. It was previously generated by the CakePHP form helper, however, I made sure that the div is replaced by the exact same name, class, id, etc... It's identical to the one that appears when the page loads
Here is the form in my view
echo $this->Form-create('Arrival');
echo $this->Form->input('room_id',array('options' => $room_numbers, 'label'=>'Room Number'));
?>
<div id="room_rate_update">
<?php
echo $this->Form->input('room_rate', array('label' => 'Room Rate (numbers only)'));
?>
</div>
<div id = "security_deposit_update">
<?php
echo $this->Form->input('security_deposit',array('label' => 'Security Deposit (numbers only)'));
?>
</div>
<?php
echo $this->Form->input('balance_upon_arrival',array('label' => 'Balance Due Upon Arrival'));
Here is the JS helper and jQuery function for the updates
//if someone changes the room_rate, this should update the deposit amount
$(document).ready(function(){
$("#ArrivalRoomRate" ).change(function() {
alert('test');
});
});
//populates the room rate when the room is selected
$this->Js->get('#ArrivalRoomId')->event('change',
$this->Js->request(array(
'controller'=>'Arrival',
'action'=>'getRoomRate'
), array(
'update'=>'#room_rate_update',
'async' => true,
'method' => 'post',
'dataExpression'=>true,
'data'=> $this->Js->serializeForm(array(
'isForm' => false,
'inline' => true
))
))
);
Here is the view for the JS helper POST request
//room_rate_update.ctp
<div class="input text required">
<label for="ArrivalRoomRate">Room Rate </label><input name="data[Arrival][room_rate]" maxlength="10" type="text" id="ArrivalRoomRate" required="required" value="<?php echo $room_rate; ?>">
</div>
So, as I stated. Prior to selecting a room_id, the "test" is triggered. After I select a value
You should have another function, for instance :
function init ()
{
$("#ArrivalRoomRate" ).change(function() {
alert('test');
});
}
After all content refreshed, then call it once. Otherwise, when all content refreshed, this event handler will be invalid for new content, coz it's partial rendering.
You can try with a delegate(aka live) event handler like following:
$(document).ready(function(){
$("body" ).on("change", "#ArrivalRoomRate", function() {
alert('test');
});
});
If you have problem with .on() with jQuery version, then you can use .live() with old jQuery like following:
$("#ArrivalRoomRate").live("click", function() {
alert("test");
});

Cakephp best way to create secret input

Okay so i have a combobox with two options.
Now if one of the options is selected a new input field should appear.
echo $this->Form->input('group_id', array( 'id' => 'groupId'));
echo $this->Form->input('clientid',array( 'type' => 'hidden', 'id' => 'id_client',));
And for that i would use Jquery to check the values
<script>
$(document).ready(function () {
$("#groupId").change(function () {
if($(this).val() == 2){
// do set visible
}
})
});
</script>
My question is: how can i change the type of the field to visible? i have tried: $('#groupId').show(); also $('#clientid').get(0).type = 'text';
But didnt seem to work and i am starting to wonder if this is the best way of doing such a thing?
$(this).attr('type', 'text');
You're doing it wrong.
type="hidden" is not appropriate to hide UI elements (form fields or anything else).
You should instead use the CSS attribute display. Change your clientid input type to "text". When groupId is not 2, set display: none on your clientid input. When it's 2, set display: block.
With jQuery, you can use $('#clientid').show() and .hide().
For instance:
<select id="groupId"><!-- options... --></select>
<input type="text" id="clientId" />
<script>
$(document).ready(function () {
function showHideClient() {
var show_client = $(this).val() == 2;
$("#clientId").toggle(show_client); // hide or show
}
// we bind the "change" event to the hide/show checking
$("#groupId").change(showHideClient);
// and we call it at page load to hide the input right away if needed
showHideClient();
});
</script>

CJUIDialog doesnt work with CListView pager Controller

I have CListView and inside im redering a view that has a button, when clicked it opens a CJUIDialog.
But when i go through to the next page with the page controller. The CJUIDialog content loads to the page without clicking the button.
Any idea why it's coming like that?
It'll be great if anyone can help me out.
Thanks!
Ok, Yii generate the ids for lot of controls in an automatic way, so to avoid collision with events I recommend you to take out the interaction handling out of the item view in the following way:
In the page where the CListView is generated:
$this->widget('zii.widgets.CListView', array(
'dataProvider'=>$dataProvider,
'itemView'=>'_post', // refers to the partial view named '_post'
'sortableAttributes'=>array(
'title',
'create_time'=>'Post Time',
),
));
$this->beginWidget('zii.widgets.jui.CJuiDialog', array(
'id'=>'dialog',
'options'=>array(
'title'=>'Dialog',
'autoOpen'=>false,
),
));
$this->endWidget('zii.widgets.jui.CJuiDialog');
In the item view page:
echo CHtml::htmlButton('Button',array('onclick' => '$("#dialog").dialog("open");'));
In case you need to do something with the data row (like using the id property of that data), you can create a custom javascript function that will receive the data when the button is clicked.
echo CHtml::htmlButton('Button',array('onclick' => 'myFunction('.$data->id.')'));
And the previous example then would be:
<?php
$this->widget('zii.widgets.CListView', array(
'dataProvider'=>$dataProvider,
'itemView'=>'_post', // refers to the partial view named '_post'
'sortableAttributes'=>array(
'title',
'create_time'=>'Post Time',
),
));
$this->beginWidget('zii.widgets.jui.CJuiDialog', array(
'id'=>'dialog',
'options'=>array(
'title'=>'Dialog',
'autoOpen'=>false,
),
));
$this->endWidget('zii.widgets.jui.CJuiDialog');
?>
<script type="text/javascript">
function myFunction(id) {
// you can put whatever you need inside the dialog
$("#dialog").html(id);
// open the dialog
$("#dialog").dialog("open");
}
</script>

Categories