jeudi 6 décembre 2018

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?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire