0

This is my code:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Example Multiple Cookie</title>
</head>
<body>



Name: <input type="text" id="name">
    Email: <input type="text" id="email">
    Company Name: <input type="text" id="companyName">

    <input type="button" value="Set Cookie" onclick="setCookie()">
    <input type="button" value="Get Cookie" onclick="getCookie()">

<script type="text/javascript">
function setCookie(){
    var object1 = [];
    object1.name = document.getElementById('name').value;
    object1.email = document.getElementById('email').value;
    object1.companyName = document.getElementById('companyName').value;

    var jsonString = JSON.stringify(object1);
    document.cookie = jsonString;
}

function getCookie(){
    if(document.cookie.length != 0){
        var object2 = JSON.parse(document.cookie);
        alert("Name= "+object2.name+"\nEmail= "+object2.email+"\nCompany Name= "+object2.companyName);
    }else{
        alert("Cookie is not set yet");
    }
}
</script>
</body>
</html>

This is the console log:

VM347:1 Uncaught SyntaxError: Unexpected token 'N', "Name=abc; "... is not valid JSON
at JSON.parse ()
at getCookie (8.3_multiple_cookie_using_object.php:30:36)
at HTMLInputElement.onclick (8.3_multiple_cookie_using_object.php:14:64)
getCookie @ 8.3_multiple_cookie_using_object.php:30
onclick @ 8.3_multiple_cookie_using_object.php:14

Note: I have passed abc,[email protected] and abc into name,email and companyName input fields respectively.

8
  • 1
    document.cookie is never JSON. A cookie can be, but dicument.cookie never is as it is all cookies, name and value Commented Sep 21, 2022 at 13:37
  • This has nothing whatsoever to do with PHP. Edited your post for you. Next time please only tag stuff which is actually relevant to the issue, not just a list of all the tech your application is using somewhere. See also How to Ask and What are tags, and how should I use them? - thanks. Commented Sep 21, 2022 at 13:40
  • Tip: log document.cookie to your console at the start of your getCookie function, and see what it actually contains Commented Sep 21, 2022 at 13:41
  • @ADyson Ok, I'll take care the next time Commented Sep 21, 2022 at 13:42
  • Name=abc; [email protected]; companyName=abc; [] Commented Sep 21, 2022 at 13:44

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.