Like button and routing issue

Hi,
I’m building a like button on my project pages.
Inspired by the code of the likes plugin, I created a custom route to catch any “project/like” url and increment the likes variable of the project

 [
'pattern' => '(:any)/like',
'action'  => function ($slug) {

  if ($page = page($slug)) {
    $counter = $page->increment('likes',1)->content()->get('likes');
    $page->update([ 'likes' => $counter ]);
    return strval( $counter );
  }

}

]

In my main.js, a press on the like button fires an ajax load as such :

var mySlug = $btnLike.attr('data-slug');
$btnLike.children('.number_like').children('p').load("/"+mySlug + "/like", function(responseTxt, statusTxt, xhr){
        if(statusTxt == "success")
            $('.is-selected').attr('data-likes',responseTxt);
            console.log("External content loaded successfully!");
        
$btnLike.children('.number_like').children('p').html(likesFormatter(Number(responseTxt)));
        if(statusTxt == "error")
            console.log("Error: " + xhr.status + ": " + xhr.statusText);
    }); 

The issue : It only works when I am logged in to the panel. Otherwise (when mysiteUrl/panel opens the login form) I get a 500 Internal server error as a response when I press the like button.

Any idea on how to fix this ?
Thanks

Julien

1 Like

Hi @ancrenoire, and welcome to the Kirby forum.

You probably need to add impersonate in your route as Kirby does not allow unauthorized users update your content.

More info: https://getkirby.com/docs/reference/objects/kirby/impersonate

1 Like

Additonally, your code somehow doesn’t make sense, because first you increment (which already updates the page), then you update again.

So your code should be either:

$counter = $page->content()->get('likes');
$newPage = $page->update([ 'likes' => $counter + 1 ]);
return $newPage->likes()->value();

or

$newPage = $page->increment('likes', 1);
return $newPage->likes()->value();
1 Like

Thanks a lot to both of you for your help !