-1

I am trying to add and retrieve cookie using JavaScript. My code is

   function setCookie(name,value,days) {
                    var date = new Date();
                    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                    var expires = "; expires=" + date.toGMTString();            
                    document.cookie = name + "=" + value + expires + ";";
                    alert("Hello you are : "+getCookie(name)); // displaying alert message 'Hello you are :'
            }
            function getCookie(cname) { //any problem with this code?
                var rcookies = document.cookie;
                var cookiearray = rcookies.split(";");
                for (i=0;i<cookiearray.length;i++){
                    var value=cookiearray[i];
                    value=value.split("=");
                if(value[0]==cname){
                    return value[1];
                }
                }
                return "";
            }
    
    function checkCookie() {
        var user = getCookie("user");
        if (user != "") {
            alert("You are " + user); // This alert is Never displayed But it need to be. 
        } else {
            user = document.getElementById("name").value;
            alert(user); // displaying the value of text field
            setCookie("user", user, 1);
        }
    }
    <form>
     <input type="text" id="name" name="name" required="required">
     <input type="button" onclick="checkCookie();" id="buttons" name="button" value="cookie">
    </form>
   

The problem is when I click on the button it set the cookie(I saw it in 'view site information', it was there) But when I try to get the cookie using getCookie method it's not showing the cookie value saved in cookies. And also when I refresh the page and press the 'view site information' icon to see cookie again, it shows 0 cookies there. what's wrong with the code? Or any mistake I'm doing?

vinay
  • 39
  • 7
  • Why do you keep editing the code? Please do this before posting your question and make sure the problem reproduces with the code that you post. The code works: https://jsfiddle.net/d0p6gooz/ – trincot Nov 04 '17 at 10:19
  • You should not put the button in the `form` element, or it will submit the form. – trincot Nov 04 '17 at 10:23
  • Sorry Sir, Now we are with the final code. No further editing is required. I copied the actual code – vinay Nov 04 '17 at 10:24
  • I also tried to with button tag still it's not showing the value of the cookie – vinay Nov 04 '17 at 10:29
  • It works for me in the fiddle. Did you try it? There must be something else wrong in your code that you have not supplied in the question. – trincot Nov 04 '17 at 10:31
  • can anyone tell me how can I do it with form tag..??? – vinay Nov 04 '17 at 17:07
  • I added it to my answer. Please check. – trincot Nov 04 '17 at 17:09

1 Answers1

0

Your button submits the form. If you don't need to submit a form, then don't use the form tag, or else put the button outside of it. Alternatively, cancel the default action of a button click.

With this HTML (without form) it works fine:

<input id="name"><button onclick="checkCookie()">Check</button>

See it run in this fiddle

If you need the form tag, then cancel the default effect of the click by adding return false in the onclick attribute:

<form>
    <input type="text" id="name" name="name" required="required">
    <input type="button" onclick="checkCookie();return false;" id="buttons" name="button" value="cookie">
</form>

See fiddle.

Local files

When you access your web page via the file:// protocol, the support for cookies is not guaranteed: it depends on the browser. Check out:

So make sure to place your web page on a web server. You can install one on your PC in case you don't want to actually place it on the internet.

Alternatively, you could decide to use localStorage instead of cookies. That has better support for file:// protocol, and has an easier syntax anyway.

trincot
  • 317,000
  • 35
  • 244
  • 286
  • Sorry, Its a typing mistake. Actually its 0 in actual code. I will edit this one. – vinay Nov 04 '17 at 10:18
  • Yes, It's working in jsfiddle, but I don't know why, when I'm running the same code locally it's doing the same as before. – vinay Nov 04 '17 at 10:38
  • You'll need to provide something that is reproducible. – trincot Nov 04 '17 at 10:39
  • I'm working on a polling website. when a user attempts the poll, I want to check whether he has attempted it before or not using cookies. The code is already given in the question asked. – vinay Nov 04 '17 at 11:07
  • Yes, This also working in jsfiddle. But why it's not working when I'm running the same code in a local file saved on my computer? I don't know what actually I'm doing wrong in this. But thanks man for your attempts. – vinay Nov 05 '17 at 06:16
  • Cookie support for local file is lacking in some browsers by default. See addition to my answer. – trincot Nov 05 '17 at 07:13
  • Bro, Thanks a lot for your help. Actually, at the end, I will run this code in JSP project. I was just trying to first make a local file test if it's working then include it in the mainstream. Your suggestion worked, I just pasted the same code in a JSP file and its working. Thanks, man. – vinay Nov 05 '17 at 07:39
  • Oohh yes, why not. – vinay Nov 05 '17 at 09:46