Silverstripe Version:
4.9 Question:
Hi! I have a Parent page (blog page ) with children of blog (selected blog). I loop all the children blog in the blog page which I want to have a like functionality.
Can anybody share an idea on how to connect to the database in just a click of a button that will increment the data of like in selected blog?
My project doesn’t have a login system but I just want to know how to increment a data from frontend to the backend using javascript and php.
That’ll give you a unique button for each post with a click handler to POST the PostPage ID to a controller.
Assuming you already have a controller for /blog, add “like” to the allowed actions:
private static $allowed_actions = ['like'];
Write a like function to increment and save the record:
public function like(HTTPRequest $request)
{
# If it's not ajax we don't want to know
if ($request->isAjax())
{
# Set a pessimistic default
$json = ['success' => false];
# Get the id from the data attribute on the button we sent
$id = $request->postVar('id');
# Use it to the find the post page. Change PostPage to w/e yours is
$post = PostPage::get()->byID($id);
# If we found a page
if ( ! empty($post))
{
# Increment the like's variable
$post->Likes = $post->Likes + 1;
$post->write();
# Success!
$json = ['success' => true];
}
return json_encode($json);
}
}
Lastly, add the “like” field to your page in it’s $db definition: