Blog Like Functionality

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.

Any idea is much appreciated. Thank you

Have you considered GitHub - markguinn/silverstripe-fb-like-button: Super simple Silverstripe extension to add Facebook like buttons to pages.

Making some assumptions here…

In your HTML where you loop your children have a button something like:

<% loop $Children %>
<button type="button" class="blog-like-button" data-id="$ID"></button>
<% end_loop %>

In jQuery:

$('.blog-like-button').click(function()
{
    $.post('/blog/like', {'id': $(this).attr('data-id')}, function (resp)
    {
        // Handle resp(onse)
    }, 'json');

});

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:

private static $db = [
    'Likes' => 'Int'
];
3 Likes

Shouldn’t be it $(this).data('id')?

@ntd Thanks I had it wrong. Can use .data(). I prefer the .attr but I had it wrong for that too. Edited.