Saturday, 6 May 2023

logic for adding likes without a separate html request

I have implemented the logic of adding likes to articles:

html

<a href="/article/?type=heart" class="comments-sub-header__item like-button ">
    <div class="comments-sub-header__item-icon-count">  </div>
</a>

<a href="/article/?type=finger" class="comments-sub-header__item like-button ">
    <div class="comments-sub-header__item-icon-count">  </div>
</a>

php

model

public function hasLikedToday(string $type)
{
    $articleLikesJson = Cookie::get('article_likes', '{}');

    $articleLikes = json_decode($articleLikesJson, true);

    if (!array_key_exists($this->id, $articleLikes)) {
        return false;
    }

    if (!array_key_exists($type, $articleLikes[$this->id])) {
        return false;
    }

    $likeDatetime = Carbon::createFromFormat('Y-m-d H:i:s', $articleLikes[$this->id][$type]);

    return !$likeDatetime->addDay()->lt(now());
}

public function setLikeCookie(string $type)
{
    $articleLikesJson = Cookie::get('article_likes', '[]');

    $articleLikes = json_decode($articleLikesJson, true);

    $articleLikes[$this->id][$type] = now()->format('Y-m-d H:i:s');

    $articleLikesJson = json_encode($articleLikes);

    return cookie()->forever('article_likes', $articleLikesJson);
}

controller

public function postLike($id, Request $request)
{
    $article = Article::find($id);

    if (!$article) {
        return abort(404);
    }

    $type = $request->input('type');

    if ($article->hasLikedToday($type)) {
        return response()
            ->json(
                [
                    'message' => 'You have already liked the Article ' . $article->id . ' with ' . $type . '.',
                ]
            );
    }

    $cookie = $article->setLikeCookie($type);

    $article->increment("like_{$type}");

    return response()
        ->json(
            [
                'message' => 'Liked the Article ' . $article->id . ' with ' . $type . '.',
                'cookie_json' => $cookie->getValue(),
            ]
        )
        ->withCookie($cookie);
}

js

$(function() {
  $.ajaxSetup({
    headers: {
      'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
    },
  });

  $('.like-button').on('click', function(event) {
    event.preventDefault();
    var targetElement=$(this);

    let href = $(this).attr('href');

    $.ajax({
      url: href,
      type: 'POST',
      success: function() {
        if (targetElement.hasClass('active')) { 
          return false;
        }

        else {
          var counter = targetElement.find('.comments-sub-header__item-icon-count');
          var current = parseInt(counter.html());

          counter .html(current + 1)
      
            targetElement.addClass('active');
        }
     },
    });
  });
});

Now it turns out that both types of likes have a separate html page like /article/11?type=heart and /article/11?type=finger

Because of these links to the page, Google software swears, and gives such an error

the server returned a 405 method not allowed

Can I somehow keep all this functionality in a simple way, but make it so that the like request is not a POST and does not have a link so as not to receive such an error?



from logic for adding likes without a separate html request

No comments:

Post a Comment