cakephp updating elements - ajax

I have an index view which has some elements on it .
index controller code;
$userID = $this->Authsome->get('id');
$qnotes = $this->Qnote->getnotes($userID);
$this->set('qnotes', $qnotes)
$this->render();
elements have been added to the page using
index view code
<?php echo $this->element('lsidebar'); ?>
now the Issue is I also Have an add controller.
add controller code
function add() {
if(!empty($this->data)) {
unset($this->Qnote->Step->validate['qnote_id']);
$this->Qnote->saveAll($this->data);
$this->Session->setFlash('New Note Template has been added.','flash_normal');
}
}
now what I am trying to achieve is once I add a Qnote i want the element('lsidebar') updated
for the new Qnote.
I am Using the Ajax helper. found at http://www.cakephp.bee.pl/
also Here the add qnote View Code :
<?php echo $ajax->submit(
'Submit', array(
'url' => array(
'controller'=>'qnotes',
'action'=>'add')
));
I know its sound like a noob question . can Somebody point me in the right direction atleast.
I have tried everything i could think off. I bet the solution something easy which i didnt think off
help :)

If you want to dynamically update a sidebar with information that is submitted via ajax, there should be a "success" option in your ajax post that would allow you to fire a specific javascript action when the post is finished (or succeeds). You should write a small javascript ajax function to reload the contents of your sidebar when the post succeeds.
See this other stackoverflow answer: CakePHP ajax form submit before and complete will not work for displaying animated gif

Related

client side validation not working for model window / ajax-loaded-form in yii

I am using Yii-user extension in the main layout i have a sign up link which is common to all the Cmenu
view/main layout
echo CHtml::link('Signup','#',array('id'=>'regi'));
$("#regi").click(function(){
$.ajax({
type:'GET',
url:'<?php echo Yii::app()->request->baseUrl;?>/index.php/user/registration',
success:function(res){
$("#dispdata").show();
$("#dispdata").html(res);
}
});
});
<div id="dispdata"><div>
**yii user extension **renders this perfectly and even submit its correctly if form values a re valid.
but if the values are incorrect and blank it redirect to url .../user/registration
which is not what my need .I need guidance what do i do such that if the values are incorrect or blank it should not redirect and display the errors in model window.
I did tried but hardly could get the satisfied results
if i place the following the model window itself doesnt appear what do i do
module registrationController i placed
....//some code here (**in yiiuser register controller**)
if ($model->save()) {
echo CJSON::encode(array(
'status'=>'success',
));
}
....//some code here...
Yii::app()->clientScript->scriptMap['jquery.js'] = false;
$this->renderPartial('registration',array('model'=>$model,),false,true);
in module view registration
<?php echo CHtml::ajaxSubmitButton(Yii::t('registration'),CHtml::normalizeUrl(array('user/registration','render'=>false)),array('dataType'=>'json',
'success'=>'function(data) {
if(data != null && data.status == "success") {
$("#registration-form").append(data.data);
}
}')); ?>
can anyone please guide me am working past 10 ten days tried every hook or crook method but could not obtain the results......how can the model window with client side validation be done appear..... Please guide me or let me know something better can be done
rules in registration model
if (!(isset($_POST['ajax']) && $_POST['ajax']==='registration-form')) {
array_push($rules,array('verifyCode', 'captcha', 'allowEmpty'=>!UserModule::doCaptcha('registration')));
as well was not with attributes for reqired field
have changed to
array_push($rules,array('verifyCode', 'captcha','message' => UserModule::t("captcha cannot be blank.")));
and added the verifycode to required field
yet not working,
The simple way is using render method in your Ajax action and creating empty layout for this action. If you do so, validation scripts will be included in the server response. Also you need to exclude jquery.js and other script with Yii::app()->clientScript->scriptMap and include them in main layout always.

ajaxbutton how to prevent refresh of the page

I succeed to use Ajax with Yii framework.
I renderPartial a form from within a list of post.
What I want to do is to prevent refresh when the user click on the ajaxbutton in the form.
In the beginning of the form I used the following code to activate ajax
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'post-form',
'enableAjaxValidation'=>true,
'enableClientValidation'=>true,
)); ?>
and at the end of the page I simply have the ajaxbutton
<?php echo CHtml::ajaxSubmitButton('Save'); ?>
in the action controller I have the following
if(isset($_POST['ajax']) && $_POST['ajax']==='comment-form')
{
echo CActiveForm::validate($comment);
Yii::app()->end();
}
When I click on the ajax button, it saves the data but refresh the page, so it display the form.
What I want is to stay on the page.
Is anyone to help ?
Thank you in advance.
you can prevent the page from refresh, or ask the user if he's sure he want to leave the page by this code:
window.onbeforeunload = function() {
return "Dude, are you sure you want to leave? Think of the kittens!";
}
you can check this question: Prevent any form of page refresh using jQuery/Javascript
I think you have some thing like $this->redirect( ... ));
in your controller after $model->save() , right?
so don't redirect there

cakephp ajax pagination works only once - scripts are not evaluatedd?

I followed tutorial from cakephp site but pagination with ajax works only once - the content is updated and its ok. But for the second time I click some page-link the whole page is reloaded - I think that click() event handlers are not binded again when content is refreshed by ajax - I don't know why... I am using this:
$this->Paginator->options(array(
'update' => '#content',
'evalScripts' => true
));
When I load page in the source code there is:
« Previous
$(document).ready(function (){
$("#link-925538478").bind("click", function (event) {
$.ajax({dataType:"html", success:function (data, textStatus){
$("#content").html(data);}, url:"\/final\/books\/index\/page:10\/sort:id\/direction:desc"});
return false;});
...
When I click for example next page (for the first time), everything is refreshed (the link hrefs also so it works) but the scripts are not reloaded so no click events are binded I think and clicking next page again just uses the link.
This is strange because I added this just after the pagination links:
<script>
$(document).ready(function (){
alert('yes');
});
</script>
And the alert is shown after first ajax refresh...
And I set up this thing ofc. <?php echo $this->Js->writeBuffer(); ?> at the end...
-------------------edit
I recognised that its not the paginator - for the following 2 links:
<?php echo $this->Js->link('link1', array('author' => 'abc'), array('update' => '#content')); ?>
<?php echo $this->Js->link('link2', array('author' => '123'), array('update' => '#content')); ?>
Its the same - when I click link1 its ajax, then when I click link2 there is normal reload - so it's somthing with script evaluation after ajax refresh... What that might be?
I am setting up JSHelper like this:
var $helpers = array('Js' => array('Jquery'));
I figured it out!!!
It's because ajax request sets the layout to app/View/Layouts/ajax.ctp and ajax.ctp is:
<?php echo $this->fetch('content'); ?>
I had to add this line
<?php echo $this->Js->writeBuffer(); ?>
To ajax.ctp to write java scripts (so the ajax links work after ajax request).
And now pagination works perfect!!!
Cake php Ajax Paginator not seems to be working fine. I had similar issues also.
I would recommend you to use the cakephp plugin Cakephp-DataTable
This plugin has implemented the pagination and it has most of the features by default. They have also provided documentation and if you find any difficulty in implementing please go throught the issues section
Also the developer is very responsive and can get clarifications for that plugin if you have any.

Yii, ajax, Button. How to prevent multiple JS onclick bindings

(First of all English is not my native language, I'm sorry if I'll probably be mistaken).
I've created Yii Web app where is input form on the main page which appears after button click through ajax request. There is a "Cancel" button on the form that makes div with form invisible. If I click "Show form" and "Cancel" N times and then submit a form with data the request is repeating N times. Obviously, browser binds onclick event to the submit button every time form appears. Can anybody explain how to prevent it?
Thank you!
I've had the exact same problem and there was a discussion about it in the Yii Forum.
This basically happens because you are probably returning ajax results with "render()" instead or renderPartial(). This adds the javascript code every time to activate all ajax buttons. If they were already active they will now be triggered twice. So the solution is to use renderPartial(). Either use render the first time only and then renderPartial(), or use renderPartial() from the start but make sure the "processOutput" parameter is only set to TRUE the first time.
Solved!
There was two steps:
First one. I decided to add JS code to my CHtml::ajaxSubmitButton instance that unbind 'onclick' event on this very button after click. No success!
Back to work. After two hours of digging I realized than when you click 'Submit' button it raises not only 'click' event. It raises 'submit' event too. So you need to unbind any event from whole form, not only button!
Here is my code:
echo CHtml::submitButton($diary->isNewRecord ? 'Создать' : 'Сохранить', array('id' => 'newRecSubmit'));
Yii::app()->clientScript->registerScript('btnNewRec', "
var clickNewRec = function()
{
jQuery.ajax({
'success': function(data) {
$('#ui-tabs-1').empty();
$('#ui-tabs-1').append(data);
},
'type': 'POST',
'url': '".$this->createUrl('/diary/newRecord')."',
'cache': false,
'data': jQuery(this).parents('form').serialize()
});
$('#new-rec-form').unbind();
return false;
}
$('#newRecSubmit').unbind('click').click(clickNewRec);
");
Hope it'll help somebody.
I just run into the same problem, the fix is in the line that starts with 'beforeSend'. jQuery undelegate() function removes a handler from the event for all elements which match the current selector.
<?php echo CHtml::ajaxSubmitButton(
$model->isNewRecord ? 'Add week(s)' : 'Save',
array('buckets/create/'.$other['id'].'/'.$other['type']),
array(
'update'=>'#addWeek',
'type'=>'POST',
'dataType'=>'json',
'beforeSend'=>'function(){$("body").undelegate("#addWeeksAjax","click");}',
'success'=>'js:function(data) {
var a=[];
}',
),
array('id'=>'addWeeksAjax')
); ?>
In my example I've added the tag id with value 'addWeeksAjax' to the button generated by Yii so I can target it with jQuery undelegate() function.
I solved this problem in my project this way, it may not be a good way, but works fine for me: i just added unique 'id' to ajax properties (in my case smth like
<?=CHtml::ajaxLink('<i class="icon-trash"></i>',
$this->createUrl('afisha/DeletePlaceAjax',
array('id'=>$value['id'])),
array('update'=>'.data',
'beforeSend' => 'function(){$(".table").addClass("loading");}',
'complete' => 'function(){$(".table").removeClass("loading");}'),
array('confirm'=>"Уверены?",'id'=>md5($value['id']).time()))
?>
).
Of course, you should call renderPartial with property 'processOutput'=true. After that, everything works well, because every new element has got only one binded js-action.
text below copied from here http://www.yiiframework.com/forum/index.php/topic/14562-ajaxsubmitbutton-submit-multiple-times-problem/
common issue...
yii ajax stuff not working properly if you have more than one, and if
you not set unique ID
you should make sure that everything have unique ID every time...
and you should know that if you load form via ajax - yii not working
well with it, cause it has some bugs in the javascript code, with die
and live
In my opinion you should use jQuery.on function. This will fire up event on dynamically changed content. For example: you're downloading some list of images, and populate them on site with new control buttons (view, edit, remove). Example structure could looks like that:
<div id="img_35" class='img-layer'>
<img src='path.jpg'>
<button class='view' ... />
<button class='edit' ... />
<button class='delete' ... />
</div>
Then, proper JS could look like this ( only for delete, others are similiar ):
<script type="text/javascript">
$(document).on('click', '.img-layer .delete', function() {
var imgId = String($(this).parent().attr('id)).split('_')[1]; //obtain img ID
$.ajax({
url: 'http://www.some.ajax/url',
type : 'POST',
data: {
id: imgId
}
}).done({
alert('Success!');
}).fail({
alert('fail :(');
});
}
</script>
After that you don't have to bind and unbind each element when it has to be appear on your page. Also, this solutiion os simple and it's code-clean. This is also easy to locate and modify in code.
I hope, this could be usefull for someone.
Regards
. Simon

$ajax->submit Does Not Go To Controller

I am using cakephp and pippoacl plugin and I simply cannot add a new role. What I modify in the plugin is to make the submit using ajax, something like this in my view (add.ctp):
<?php echo $ajax->submit(
'submit',
array(
'url' => array('controller' => 'roles', 'action' => 'add'),
'before' => 'beforeSubmitAdd();',
'complete' => 'completeSubmitAdd(request);'
)
);
?>
When the add.ctp gets loaded for the first time, I can print_r something from the controller. But the ajax submit above only executes the javascript on 'before' and 'complete'. I check on the firebug, the response is blank.
On my controller:
function add() {
print_r("start");
if (!empty($this->data)) {
print_r("add new role");
// save new role
}
}
I use ajax submit for user and I don't have any problem adding new user. Is there any idea where I should check? I have been comparing the user and role code for a week and I have asked a friend to look at my code, too, but we still cannot find what causes this.
Thanks in advance! :D
I am not so familiar with the Ajax helper, but I haven't using it from so long that I can't remember what is it doing :).
Back to the problem.
Did you check if the requested URL in the Ajax address is correct? This should work straightforward, but it's possible that the url to be invalid.
Are you using Security component (even just adding it on the var $components variable)?. This could lead to blank screen especially if you modifying the fields in the form somehow. Try to remove it and see if it's working without.
Finally I would say how I would do it with jQuery.
Following code should do the job:
$(document).ready(function(){
$('form').live('submit', function(){ //handles also dynamically loaded forms
var form = $(this).addClass('loading'); //indicate somehow that the form has been submitted
$('#content').load($(this).attr('action'), $(this).serialize(), function(){
form.removeClass('loading');
});
})
});
This will handle all submits in the forms of the system, but you can modify of course.

Resources