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,abc@gmail.com and abc into name,email and companyName input fields respectively.

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
  • 1
    document.cookie is never JSON. A cookie can be, but dicument.cookie never is as it is all cookies, name and value – Jaromanda X Sep 21 '22 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 [ask] and [What are tags, and how should I use them?](https://stackoverflow.com/help/tagging) - thanks. – ADyson Sep 21 '22 at 13:40
  • Tip: log `document.cookie` to your console at the start of your getCookie function, and see what it _actually_ contains – ADyson Sep 21 '22 at 13:41
  • @ADyson Ok, I'll take care the next time – Crazy Programmer Sep 21 '22 at 13:42
  • Name=abc; Email=abc@gmail.com; companyName=abc; [] – Crazy Programmer Sep 21 '22 at 13:44
  • Your object should be defined as `{}`, not `[]`. It's throwing off the encoding. – aynber Sep 21 '22 at 13:46
  • Also, if that's what `console.log(document.cookie);` shows in your `getCookie`, it is most definitely not json, and does not match what `setCookie` is supposed to create. – aynber Sep 21 '22 at 13:49
  • @aynber Thanks, the problem has been solved – Crazy Programmer Sep 21 '22 at 13:58

0 Answers0