Laravel cookie - не удаляется с помощью ajax-запроса - PullRequest
0 голосов
/ 06 декабря 2018

У меня есть список "идей" в моей базе данных.Каждый раз, когда пользователь нажимает кнопку, отображается новая случайная идея (и добавляется в файл cookie).Если идей не осталось, на кнопке появляется сообщение, чтобы начать все сначала (= удалить cookie и получить случайное представление).

Вышеописанное работает до сих пор.Проблема в том, чтобы начать все сначала (= удалить куки и получить случайную идею снова).

В моем вызове ajax есть:

$.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);
    }
});

В поле ввода с идентификатором noideas Я устанавливаю, если не осталось идей.

В моей функции (в контроллере) у меня есть:

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);
}

Проблема в том, что куки не удаляются.Что я делаю не так?

1 Ответ

0 голосов
/ 06 декабря 2018

Полагаю, что вы забыли установить cookie после получения random_idea, когда в запросе указано «noidea», или забыли удалить истинное значение #noideas.

Также:

  1. Вам не нужно проверять !in_array($random_idea->id,$ideas), потому что оно реализовано в вашем запросе ::whereNotIn('id', $ideas).
  2. Вам не нужно забывать cookie, когда запрос имеет "noideas", потому что он выглядит как вынужно сбросить (не забыть) cookie после получения случайной идеи.

Извините, позвольте мне переписать код:

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 автоматически преобразует $ random_idea в json, если $random_idea не является нулевымТогда Аякс:

$.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);
    }
});
...