简体   繁体   English

Laravel会话变量在页面加载后由ajax设置时删除

[英]Laravel session variable remove after page load when set by ajax

I have a simple ajax code which saves the category and subcategory id in session. 我有一个简单的Ajax代码,可在会话中保存类别和子类别ID。 These two variables save in session but on next reload both values does not exist in session. 这两个变量保存在会话中,但是在下次重新加载时,会话中不存在这两个值。 This session issue is only with ajax. 此会话问题仅与ajax有关。 I have other points where i am storing and retrieving session and it is working file. 我在其他地方存储和检索会话,并且它是工作文件。 Here is my ajax call. 这是我的ajax电话。

    $("#search-select-category").on("click", function () {
    console.log("sending ajax");

    $.ajax({
        type: "POST",
        url: $("#select-category-search").prop('action'),
        data: {
            "_token": $("#select-category-search").find('input[name=_token]').val(),
            "category_id": $("input[name='category-search']").val(),
            "subcategory_id": $("input[name='subcategory-search']").val(),
        },
        success: function (response) {
            var response = JSON.parse(response);
            console.log(response.message);
            if(response.error) {
                console.log("error is here");
                $(".search-category-error span").text(response.message);
                $(".search-category-error").show();
            }
            else {
                console.log("selection is good");
                $(".search-category-error").slideDown();
                $(".select-category-modal").modal('hide');
            }
        }
    });
});

and the function that executes on ajax call is as follows 并且在ajax调用上执行的函数如下

public function ajax_select_category_search(Request $request) {

    $error = false;
    $message = "";

    if (empty($request->category_id) || empty($request->subcategory_id)) {
        $error = true;
        $message = "Category or Sub Category is not selected";
    }

    if ($error == false) {
        session(['category_search' => $request->category_id]);
        session(['subcategory_search' => $request->subcategory_id]);
    }

    $response['error'] = $error;
    $response['message'] = $message;

    echo json_encode($response);
    die();
}

I have tried using file and database session but same problem in both cases. 我尝试使用文件和数据库会话,但在两种情况下都存在相同的问题。 I am using laravel 5.3 Session class is also imported in the class i am using and there are no errors when i use this function. 我使用的是laravel 5.3,会话类也已导入到我正在使用的类中,使用此功能时没有错误。

The reason is i had a die() in the php ajax function. 原因是我在php ajax函数中有die()。 I don't know why remove added session when you have a die() in your ajax call. 我不知道为什么在ajax调用中有die()时删除添加的会话。 However i removed the die() and it worked perfectly. 但是我删除了die(),它工作得很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM