Ad

Cookie Not Being Saved In OctoberCMS

- 1 answer

I'm trying to save an item in a cookie via octobercms ajax, but the cookie is not being saved:

HTML

<button
    data-request="onSaveItem"
    data-request-data="item_id: 12345">Save item</button>

PHP

function onSaveItem() {
    $item_id = Input::get('item_id');
    Cookie::forever('saved_item', $item_id);
}

So, when I try to retrieve the cookie on page start, it returns NULL:

function onStart() {
    var_dump(Cookie::get('saved_item'));
}

// output: NULL
Ad

Answer

Using cookies took me a while to understand as well. I hope I wrote this clear enough for you. Basically you aren't returning the cookie to the browser to add it to the application storage. I created an example page you can see here.

The first example is a common html form.

{{ form_open({request:'onSaveItemRedirect'}) }}
    <input type="text" name="item_id" value="12345">
    <button>Save item</button>
{{ form_close() }}

This form sends the post information to onSaveItemRedirect. The key thing to note is the cookie queue. This allows the server to send the cooker in the header with the redirect.

function onSaveItemRedirect() {
    $item_id = Input::get('item_id');
    $cookie = Cookie::forever('saved_item', $item_id);
    Cookie::queue($cookie);
    return Redirect::refresh();
}

This second example uses the AJAX API and is a bit more complicated. Notice that I am using a partial and the data-request-complete method. This will update the partial using a JavaScript function, updateCookie(), with the new cookie on AJAX complete.

<h3 id="cookiePartial">{% partial 'cookie/test' %}</h3>
{{ form_ajax('onSaveItemAjax', {'complete' : 'updateCookie()' }) }}
    <input type="text" name="item_id" value="12345">
    <button>Save item</button>
{{ form_close() }}

Script:

<script>
function updateCookie() {
    $.request('onUpdateCookiePartial', {
        update: {'cookie/test': '#cookiePartial'}
    });
}
</script>

PHP: Notice here that you should return a response with the cookie information. When the response is returned and completed then the AJAX API sends a request to the onUpdateCookiePartial(). It is good practice to return something when running an event handler; in this case true.

function onSaveItemAjax() {
    $item_id = Input::get('item_id');
    $cookie = Cookie::forever('saved_item', $item_id);
    return Response::json(['Success'])->withCookie($cookie);
}

function onUpdateCookiePartial() {
    return true;
}
Ad
source: stackoverflow.com
Ad