Search code examples
ajaxlaravellaravel-5cookiesresponse

Laravel cookie - not deleting with ajax request


I have a list of "ideas" in my database. Every time the user clicks on a button a new random idea is shown (and added to a cookie). When there are no ideas left a message is shown in the button to start over (= delete cookie and get random idea).

The above works so far. The problem is to start over (= delete the cookie and get a random idea again).

In my ajax call have I have:

$.ajax({
    type: "POST",
    url: "/idea",
    data: { noideas: $("#noideas").val() },
    success: function(response) {
        if(response == false)
        {
            $(".card").fadeOut(function(){
                $(this).remove();

                $('<div class="card card-primary">' +
                    '<div class="card-header">' +
                    '<h3 class="card-title">Einde</h3>' +
                    '</div>' +
                    '<div class="card-body">U heeft alle ideeën bekeken.</div>' +
                    '</div>').appendTo('.content').fadeIn();
            });

            $("#noideas").val('true');
            $("#idea").text("Start opnieuw.");
        }
        else
        {
            $(".card").fadeOut(function(){
                $(this).remove();

                $('<div class="card card-primary">' +
                    '<div class="card-header">' +
                    '<h3 class="card-title">' + response.title + '</h3>' +
                    '</div>' +
                    '<div class="card-body">' + response.description +
                    '</div>' +
                    '</div>').appendTo('.content').fadeIn();
            });
        }
    },
    error: function(jqXHR, textStatus, errorThrown) {
        console.log(errorThrown);
    }
});

In the input field with id noideas I set if there are no ideas left.

In my function (in controller) I have:

public function idea(Request $request)
{
    $noideas = $request->input('noideas');

    // cookie
    $ideas = Cookie::get('ideas');
    $ideas = unserialize($ideas);

    $random_idea = Idea::whereNotIn('id', $ideas)->inRandomOrder()->first();

    if($random_idea)
    {
        if(!in_array($random_idea->id,$ideas))
        {
            $ideas[] = $random_idea->id;
        }
    }
    else
    {
        $random_idea = false;
    }

    Cookie::queue('ideas', serialize($ideas));

    if($noideas == "true")
    {
        Cookie::queue(
            Cookie::forget('ideas')
        );

        $ideas = array();
        $random_idea = Idea::whereNotIn('id', $ideas)->inRandomOrder()->first();
    }

    return response()->json($random_idea);
}

The problem is that the cookies aren't deleted. What am I doing wrong?


Solution

  • I suppose that you forget to set cookie after getting random_idea, when request has "noidea", or you forget to remove true value of #noideas.

    Also:

    1. You don't need to check !in_array($random_idea->id,$ideas), because it is implemented in your query ::whereNotIn('id', $ideas).
    2. You don't need to forget cookie, when request has "noideas", because it looks like you need to reset (not forget) cookie after getting random idea.

    Sorry, let me rewrite the code:

    public function idea(Request $request)
    {
        $ideas = [];
    
        if(Cookie::has('ideas') && $request->input('noideas') != 'true'){
            $ideas = Cookie::get('ideas');
            $ideas = unserialize($ideas);
        }
    
        $random_idea = Idea::whereNotIn('id', $ideas)->inRandomOrder()->first();
    
        if($random_idea){
            $ideas[] = $random_idea->id;
            Cookie::queue('ideas', serialize($ideas));
        }
    
        return $random_idea;  //return json or null if no unique random idea was found
    }
    

    Laravel will automatically convert $random_idea to json, if $random_idea is not null. Then ajax:

    $.ajax({
        type: "POST",
        url: "/idea",
        data: { noideas: $("#noideas").val() },
        success: function(response) {
            if(response){   //reverse codition logic
                $(".card").fadeOut(function(){
                    $('.cart-title').text(response.title);    //I rewrite this part, because you don't need to remove element and render it every time
                    $('.cart-body').text(response.description);
                    $(this).fadeIn();
                });
    
                $("#noideas").val('false'); //remove true value
            } else {
                $(".card").fadeOut(function(){
                    $('.cart-title').text('Einde');
                    $('.cart-body').text('U heeft alle ideeën bekeken.');
                    $(this).fadeIn();
                });
    
                $("#noideas").val('true');
                $("#idea").text("Start opnieuw.");
            }
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.log(errorThrown);
        }
    });