I am trying to implement the Ajax feature in the comments section of my blog. I have downloaded prototype-1.6.0.3.js and have placed it in the js folder inside webroot. I have made the following changes in the layout file(default.ctp)
$javascript->link(array('prototype'));
Also, following code has been added to controllers
var $helpers = array('Html', 'Form', 'Ajax','Javascript');
This is my code in the posts_controller.php file
function view($id = null) {
if (!$id) {
$this->Session->setFlash(__('Invalid Post.', true));
$this->redirect(array('action'=>'index'));
}
$post = $this->Post->read(null,$id);
$comments = $this->Post->Comment->find('all',
array('conditions'=>array('Post.id'=>$id)));
$this->set(compact('post','comments'));
}
My code in view.ctp file
<h2>Comments</h2>
<div id="comments">
<?php foreach($comments as $comment): ?>
<div class="comment">
<p><b><?php echo $comment['Comment']['name']; ?></b></p>
<p><?php echo $comment['Comment']['content']; ?></p>
</div>
<?php endforeach; ?>
<?php echo $ajax->form('/comments/add','post',array('update'=>'comments'));?>
<?php echo $form->input('Comment.name');?>
<?php echo $form->input('Comment.content');?>
<?php echo $form->input('Comment.post_id',array('type'=>'hidden','value'=>$post['Post']['id']));?>
<?php echo $form->end('Add Comment');?>
</div>
I have added the following function in the comments_controller.php
function add() {
if (!empty($this->data)) {
$this->Comment->create();
if ($this->Comment->save($this->data)) {
$comments = $this->Comment->find('all',array('conditions'=>array('post_id'=>$this->data['Comment']['post_id']),'recursive'=>-1);
$this->set(compact('comments'));
$this->render('add_success','ajax');
} else {
$this->render('add_failure','ajax');
}
}
}
And following is the code in the add_success.ctp file
<?php foreach($comments as $comment): ?>
<div class="comment">
<p><b><?php echo $comment['Comment']['name'];?></b></p>
<p><?php echo $comment['Comment']['content'];?></p>
</div>
<?php endforeach;?>
Now the problem is that I am not able to add comments. Nothing happens when I click on the add comments button. I have manually added comments in the databse and that works. But I am having problems when I am trying the Ajax Helper.
Where is the problem??And guys, sorry for such a long question.[:(]