Reputation: 25122
I have an Article controller & model. I want to have a function that adds one to an integer when a link is clicked. So I have say a "i like" button (link) it takes me to Articles/thumbsup it will then take the thumbsup field of that article and increment it by one, then save the article, and redirect to the view.
I'm not sure how to modify records in this way. I need to load the article, modify the data and then save it.
My hope is that this be handled by javascript so noone will see the url change.
Can someone help me out here?
Thanks,
Jonesy
Thanks,
Billy
Upvotes: 0
Views: 1371
Reputation: 3250
You can do that with an AjaxRequest.
models/article.php:
function thumbsup($id = null)
{
$conditions = array('Article.id' => $id);
$this->updateAll(
array('Article.thumbsup' => 'Article.thumbsup + 1'),
$conditions
);
$article = $this->find(
'first',
array('conditions' => $conditions, 'fields' => array('Article.thumbsup'))
);
return $article['Article']['thumbsup'];
}
controllers/articles_controller.php:
function thumbsup($id = null)
{
$this->set('count', $this->Article->thumbsup($id));
$this->layout = 'ajax';
}
views/articles/thumbsup.ctp:
<?php echo $count; ?>
webroot/js/thumbsup.js:
$(document).ready(function()
{
$('.iLikeSomething').click(function()
{
$.post('http://yoursite.com/articles/incrementThumbsup/'+this.id, function(data)
{
$('#iLikeSomethingCount').html(data);
});
});
});
Html sample for clicking:
<span class="iLikeSomething" id="insertYourArticleIdHere" style="cursor: pointer;">iLike</span>
<div id="iLikeSomethingCount">0</div>
Upvotes: 1