CodeIgniter 4: Like and Dislike Functionality



PHP Snippet 1:

<script>
    $(document).ready(function() {  
        var csrfName = "<?= csrf_token(); ?>";
        var csrfHash = "<?= csrf_hash(); ?>"; 

        // if the user clicks on the like button
        $(".like-button").on("click", function() {
            var viewkey = $(this).data("viewkey");
            $clicked_btn = $(this);

            if ($clicked_btn.hasClass("fa-thumbs-o-up")) {
                action = "like";
            } else if ($clicked_btn.hasClass("fa-thumbs-up")) {
                action = "unlike";
            }

            $.ajax({
                url: "<?= base_url('/images/view_image/index'); ?>",
                type: "post",
                dataType: "json",
                data: {
                    [csrfName]: csrfHash,
                    "action": action,
                    "viewkey": viewkey,
                },
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                },
                success: function(data) {
                    var res = data;
                    csrfName = data.csrfName;
                    csrfHash = data.csrfHash;

                    if (action == "like") {
                        $clicked_btn.removeClass("fa-thumbs-o-up");
                        $clicked_btn.addClass("fa-thumbs-up");
                    } else if (action == "unlike") {
                        $clicked_btn.removeClass("fa-thumbs-up");
                        $clicked_btn.addClass("fa-thumbs-o-up");
                    }

                    // display number of likes and dislikes
                    $clicked_btn.siblings('span.likes').text(res.likes);
                    $clicked_btn.siblings('span.dislikes').text(res.dislikes);

                    // Change button styling of the other button if user is reacting the second time to image
                    $clicked_btn.siblings("i.fa-thumbs-down").removeClass("fa-thumbs-down").addClass("fa-thumbs-o-down");
                }
            });
        });
        // If the user clicks on the dislike button
        $(".dislike-button").on("click", function() {
            var viewkey = $(this).data("viewkey");
            $clicked_btn = $(this);

            if ($clicked_btn.hasClass("fa-thumbs-o-down")) {
                action = "dislike";
            } else if ($clicked_btn.hasClass("fa-thumbs-down")) {
                action = "undislike";
            }

            $.ajax({
                url: "<?= base_url('/images/view_image/index'); ?>",
                type: "post",
                dataType: "json",
                data: {
                    [csrfName]: csrfHash,
                    "action": action,
                    "viewkey": viewkey
                },
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                },
                success: function(data) {
                    var res = data;
                    csrfName = data.csrfName;
                    csrfHash = data.csrfHash;

                    if (action == "dislike") {
                        $clicked_btn.removeClass("fa-thumbs-o-down");
                        $clicked_btn.addClass("fa-thumbs-down");
                    } else if (action == "undislike") {
                        $clicked_btn.removeClass("fa-thumbs-down");
                        $clicked_btn.addClass("fa-thumbs-o-down");
                    }

                    // display number of likes and dislikes
                    $clicked_btn.siblings('span.likes').text(res.likes);
                    $clicked_btn.siblings('span.dislikes').text(res.dislikes);

                    // Change button styling of the other button if user is reacting the second time to image
                    $clicked_btn.siblings("i.fa-thumbs-up").removeClass("fa-thumbs-up").addClass("fa-thumbs-o-up");
                }
            });
        });
   });
</script>

PHP Snippet 2:

$viewkey = $this->request->uri->getSegment(4);

        if ($this->request->IsAjax()) {

            if (! empty($this->request->getPost('action')) && ! empty($this->request->getPost('viewkey')) && ! empty(session()->get('username'))) {

                $input = $where = [];

                $input = [
                    'action'    => $this->request->getPost('action'),
                    'username' => session()->get('username'),
                    'viewkey'   => $this->request->getPost('viewkey'),
                    'modified'  => date('Y-m-d H:i:s'),
                ];

                $actionCount = $this->actionModel->insertAction($input);

                return $actionCount;
            
            } 
        } 

PHP Snippet 3:

public function insertAction($input)
    {
        $db = \Config\Database::connect();
        $builder = $db->table('actions');

        $data = $where = [];

        $viewkey = $input['viewkey'];

        switch($input['action']) {

            case 'dislike':

                $data = [
                    'username'  => $input['username'],
                    'action'    => 0,
                    'viewkey'   => $input['viewkey'],
                    'modified'  => $input['modified'],
                ];

                if ($this->userLiked($viewkey) == false) {
                    
                    $builder->insert($data);
                
                } else {

                    $where = [
                        'username'  => $input['username'],
                        'viewkey'   => $input['viewkey'],
                        'action'    => 1,
                    ];

                    $builder->where($where)->delete();
                    $builder->insert($data);
                }

                break;

            case 'undislike':

                $where = [
                    'action' => 0,
                ];

                $builder->where($where)->delete();

                break;

            case 'like':

               $data = [
                    'username'  => $input['username'],
                    'action'    => 1,
                    'viewkey'   => $input['viewkey'],
                    'modified'  => $input['modified'],
                ];

                if ($this->userDisliked($viewkey) == false) {
                    
                    $builder->insert($data);
                
                } else {

                    $where = [
                        'username'  => $input['username'],
                        'viewkey'   => $input['viewkey'],
                        'action'    => 0,
                    ];

                    $builder->where($where)->delete();
                    $builder->insert($data);
                }

                break;

            case 'unlike':

                $where = [
                    'action' => 1,
                ];

                $builder->where($where)->delete();

                break;
    return $this->getActions($viewkey);
        exit(0);
    }

public function userDisliked($viewkey) 
    {
        $actionModel = new ActionModel();
        
        $where = [];

        $where = [
            'viewkey'   => $viewkey,
            'username'  => session()->get('username'),
            'action'    => 0,
        ];

        if ($actionModel->where($where)->first()) {

            return true;
        
        } else {

            return false;
        } 
    }

    public function userLiked($viewkey) 
    {
        $actionModel = new ActionModel();

        $where = [];

        $where = [
            'viewkey'   => $viewkey,
            'username'  => session()->get('username'),
            'action'    => 1,
        ];

        if ($actionModel->where($where)->first()) {

            return true;
        
        } else {

            return false;
        } 
    }

 public function getActions($viewkey)
    {
        $data = [];

        $data = [
            'csrfName'  => csrf_token(),
            'csrfHash'  => csrf_hash(),
            'dislikes'  => $this->getDislikes($viewkey),
            'likes'     => $this->getLikes($viewkey),
            'views'     => $this->getViews($viewkey),
            'favorites' => $this->getFavorites($viewkey),
        ];

        return json_encode($data);
    }