AlexanderKim
1 year ago
730
4
Laravel

Set cookie on ajax post request

Posted 1 year ago by AlexanderKim

Doing some vote up/down functionality with Ajax.

JS:

    <script type="text/javascript">
        $(document).ready(function () {
            $('.thumb-down, .thumb-up').click(function (e) {
                e.preventDefault();
                if ($(this).attr('class') == 'thumb-up') {
                    var voteValue = 1;
                } else {
                    var voteValue = 0;
                }

                var projectID = $('#project-id').text();
                
                // console.log(projectID);

                $.ajax({
                    method: 'post',
                    headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
                    url: '/vote',
                    data: {
                        vote: voteValue,
                        id: projectID
                    },
                    success: function(data) {
                        $('.thumb-count').html(data.total_count);
                        console.log(data);
                    },
                    error: function(jqxhr, status, exception) {
                        console.log('Error ' + exception);
                    }
                });
            });
        });
    </script>

Controller:

    /**
     * Vote post method
     */
    public function vote(Request $request)
    {
        $vote = new Vote;

        $vote->project_id = $request->input('id');
        $vote->vote = $request->input('vote');
        $cookie = cookie()->forever('project-' . $request->input('id'), $request->input('vote'));
        $vote->cookie = $cookie;
        
        $vote->save();

        $votes_up = Vote::where('project_id', $request->input('id'))->where('vote', '=', 1)->count();
        $votes_down = Vote::where('project_id', $request->input('id'))->where('vote', '=', 0)->count();

        if ($votes_up > $votes_down) {
            $total_count = $votes_up - $votes_down;
        } else if ($votes_down > $votes_up) {
            $total_count = $votes_up - $votes_down;
        } else {
            $total_count = 0;
        }

        return response()->json(compact('total_count'))->cookie($cookie);
    }

When user clicks vote up or down, it sends ajax post request to this controller's method, in this controller i'm setting up cookie and sending it back with response(), but how can i then check if this cookie exists on client's browser, so it won't allow to vote him again?

Please sign in or create an account to participate in this conversation.