1

my problem is that to set a cookie by click on a button is not working. I've tested it on 3 different ways.

HTML:

<!DOCTYPE html>
<html dir="ltr">
    <head> [...]
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js" type="text/javascript"></script>
        <script src="/cookies/js/jquery.cookie.js"></script>
        <script>
            document.getElementById('btnSetCookie').onclick = function () {
                $.cookie('cookie-1', 'true');
                alert('You have set the cookie: ' + jQuery.cookie('cookie-1'));
            });
            $(function () {
                $("#btnSetCookie").click(function () {
                    jQuery.cookie('cookie-2', 'true');
                    alert('You have set the cookie: ' + jQuery.cookie('cookie-2'));
                });
            });
            $(document).ready(function () {
                $("#btnSetCookie").on('click', function () {
                    $.cookie('cookie-3', 'true');
                    alert('You have set the cookie: ' + jQuery.cookie('cookie-3'));
                });
            });
        </script>
    </head>
    <body> [...]
        <button id="btnSetCookie">set cookie</button> [...]
    </body>
</html>

Any idea what's my mistake?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
J.M.
  • 11
  • 1
  • 2
  • Are you loading the page from a web server or from file system? And why THREE event handlers at the same time? AND TWO different ways to acces jQuery. The first will not work since the button does not exist at the time of the script. Please look in the console (press F12) – mplungjan Mar 02 '18 at 13:37
  • 1
    What errors are in your browser's console? I suspect that you need to set the protocol `http(s):` for the jQuery library - I found I needed to do this (depending on the browser). And the first version won't work because the element is not yet available on the page. – Andy G Mar 02 '18 at 13:39
  • what version of `jquery.cookie.js` are you using? – ztadic91 Mar 02 '18 at 15:29

1 Answers1

1

The reason this is not working for you is that you cannot set cookies if you're not running on a server. In other words, if you're serving the file in a browser locally using file://, it simply won't work.

Both your second and third option run fine. I would clean them both up and use either $ or jQuery consistently, but both work when running on a server.

Here's a demo of your code working.

$(document).ready(function () {
  $("#btnSetCookie").on('click', function () {
    $.cookie('cookie-3', 'true');
    alert('You have set the cookie: ' + $.cookie('cookie-3'));
  });
});

You could also consider using a more up-to-date version of jQuery, as well as the plugin you're using (the version you're using is no longer maintained). In fact, the newer version of the plugin is no longer dependent upon jQuery at all.

jme11
  • 17,134
  • 2
  • 38
  • 48