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

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.

Related

AJAX pagination with CakePHP

I'm struggling to get some ajax pagination with cakephp working. I've read the instructions here and various other pages on the internet eg: SO link
However I get an error in the console:
Uncaught type error undefined is not a function
Which occurs on the $(document).ready() function generated by $this->Js->writeBuffer().
Any ideas on what I'm doing wrong?
In my view index.ctp I set the paginator's options:
$this->Paginator->options(array(
'update' => '#content',
'evalScripts' => true)
);
Then carry on with the remainder of the view, in particular I render the table. The controller has fetched data to be displayed.
I output my pagination controls:
echo $this->Paginator->prev();
echo $this->Paginator->numbers();
echo $this->Paginator->next();
At the end of my view I do:
echo $this->Js->writeBuffer();
I have added the relevant helpers and components to my controller:
public $helpers = array('Js' => array('jquery'));
public $components = array(
'Paginator',
'RequestHandler'
);
In default.ctp I have included jquery by adding this to the end of the HTML (just before </body>:
<script src="https://code.jquery.com/jquery.js"></script>
It looks it works in that it generated the relevant javascript and provides the id's for the links but clicking the links just works like normal.
Functions need to exist before they are called
In default.ctp I have included jquery by adding this to the end of the HTML (just before </body>
Jquery needs to be loaded before it is used. Ensure that script tags appear in the rendered html in this order:
<script src="//code.jquery.com/jquery.js"></script>
... anything or nothing ...
<script>
$(document).ready(
...

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

Reloading everything but one div on a web page

I'm trying to set up a basic web page, and it has a small music player on it (niftyPlayer). The people I'm doing this for want the player in the footer, and to continue playing through a song when the user navigates to a different part of the site.
Is there anyway I can do this without using frames? There are some tutorials around on changing part of a page using ajax and innerHTML, but I'm having trouble wrapping my head aroung getting everything BUT the music player to reload.
Thank you in advance,
--Adam
Wrap the content in a div, and wrap the player in a separate div. Load the content into the content div.
You'd have something like this:
<div id='content'>
</div>
<div id='player'>
</div>
If you're using a framework, this is easy: $('#content').html(newContent).
EDIT:
This syntax works with jQuery and ender.js. I prefer ender, but to each his own. I think MooTools is similar, but it's been a while since I used it.
Code for the ajax:
$.ajax({
'method': 'get',
'url': '/newContentUrl',
'success': function (data) {
// do something with the data here
}
});
You might need to declare what type of data you're expecting. I usually send json and then create the DOM elements in the browser.
EDIT:
You didn't mention your webserver/server-side scripting language, so I can't give any code examples for the server-side stuff. It's pretty simple most of time. You just need to decide on a format (again, I highly recommend JSON, as it's native to JS).
I suppose what you could do is have to div's.. one for your footer with the player in it and one with everything else; lets call it the 'container', both of course within your body. Then upon navigating in the site, just have the click reload the page's content within the container with a ajax call:
$('a').click(function(){
var page = $(this).attr('page');
// Using the href attribute will make the page reload, so just make a custom one named 'page'
$('#container').load(page);
});
HTML
<a page="page.php">Test</a>
The problem you then face though, is that you wouldnt really be reloading a page, so the URL also doesnt get update; but you can also fix this with some javascript, and use hashtags to load specific content in the container.
Use jQuery like this:
<script>
$("#generate").click(function(){
$("#content").load("script.php");
});
</script>
<div id="content">Content</div>
<input type="submit" id="generate" value="Generate!">
<div id="player">...player code...</div>
What you're looking for is called the 'single page interface' pattern. It's pretty common among sites like Facebook, where things like chat are required to be persistent across various pages. To be honest, it's kind of hard to program something like this yourself - so I would recommend standing on top of an existing framework that does some of the leg work for you. I've had success using backbone.js with this pattern:
http://andyet.net/blog/2010/oct/29/building-a-single-page-app-with-backbonejs-undersc/
You can reload desired DIVs via jQuery.ajax() and JSON:
For example:
index.php
<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script type="text/javascript" src="ajax.js"></script>
<a href='one.php' class='ajax'>Page 1</a>
<a href='two.php' class='ajax'>Page 2</a>
<div id='player'>Player Code</div>
<div id='workspace'>workspace</div>
one.php
<?php
$arr = array ( "workspace" => "This is Page 1" );
echo json_encode($arr);
?>
two.php
<?php
$arr = array( 'workspace' => "This is Page 2" );
echo json_encode($arr);
?>
ajax.js
jQuery(document).ready(function(){
jQuery('.ajax').click(function(event) {
event.preventDefault();
// load the href attribute of the link that was clicked
jQuery.getJSON(this.href, function(snippets) {
for(var id in snippets) {
// updated to deal with any type of HTML
jQuery('#' + id).html(snippets[id]);
}
});
});
});

cakephp updating elements

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

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

Resources