2

I'm trying to send some data into a JSON object, and then into a cookie. But I'm getting this error when im trying to parse it: "SyntaxError: JSON Parse error: Unable to parse JSON string".

Here is the code causing the error:

function checkCookies() {
    var message;

    if(document.cookie) {
        var iCookie = document.cookie.split('=');
        console.log(iCookie);
        var iObject = JSON.parse(iCookie[1]);

        message = "Cookie finnes: " + iObject.word;
    } else {
        message = "Fant ikke cookie.";
    }
    $("#sectSavedWord").html(message);
}

And this is the code where I'm trying to create the cookie:

$("#btnSaveWords").click(function(){
        var finalWord = "";

        for (var i = 0; i < word.length; i++) {
            finalWord += word[i];
        }

        document.cookie = "info=" + JSON.stringify({"word": finalWord}) + ";expires=" + getExpireDate(7);
        document.location = "oppgave1_2.html";
    });

Can anyone point me in the right direction here? I have tried getting this to work for days now. I have used this syntax (or at least something very similar) earlier, and it has worked earlier..

2
  • finalWord is supposed to be a string, not an array. It's getting its content from the word-array, which is based on another array containing the alphabet. (var alphabet = ["a","b","c".... and so on..).. So sample data could be: "HEY!" or "LOREM IPSUM". Commented May 15, 2013 at 17:39
  • And are you sure there are no other cookies set! You really need to add in other logic! Commented May 15, 2013 at 17:40

1 Answer 1

1

Your split value iCookie[1] will have ;expires in the string

document.cookie = "info=" + JSON.stringify({"word": finalWord}) + ";expires=" + getExpireDate(7);

This is causig issue in parsing

    var iCookie = document.cookie.split('=');
    console.log(iCookie);
    var iObject = JSON.parse(iCookie[1]);
Sign up to request clarification or add additional context in comments.

1 Comment

AKA, find a getCookie method and use that to get the value. MDN is a good place to look: developer.mozilla.org/en-US/docs/DOM/document.cookie

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.