Verify whether the cookie information is in an array format

As visitors click on products on my site, I am storing their IDs in a cookie.

Each click adds the new ID to an array stored in the cookie.

This is how I set up the cookie and its current value after a few clicks:

var cookieArray = [];

cookieArray.push('582');

For example, after clicking on 3 products with IDs 582, 590, and 572:

[582%2C590%2C572]

My question: Is the format of the cookie value correct for representing an array? Does the %2C properly separate each ID?

Later, I will use PHP to retrieve this data and loop through each ID value.

Answer №1

%2 represents a comma (,) in JavaScript, so when you convert a JS array into a string and then encode it, the result will include this character.

To parse this encoded string, you can utilize PHP's unserialize function.

Another approach is to store JSON data in your cookies and then use json_decode method for parsing.

const IDs = [1, 2, 3];

document.getElementById('content').innerHTML = `
  encodeURIComponent(',') = ${ encodeURIComponent(',') }
  decodeURIComponent('%2C') = ${ decodeURIComponent('%2C') }
  
  IDs.toString() = ${ IDs.toString() }
  encodeURIComponent(IDs.toString()) = ${ encodeURIComponent(IDs.toString()) }
  
  JSON.stringify(IDs) = ${ JSON.stringify(IDs) }
  encodeURIComponent(JSON.stringify(IDs)) = ${ encodeURIComponent(JSON.stringify(IDs)) }
`;

document.cookies = `productIds=${ JSON.stringify(IDs) }`;

console.log(document.cookies);
console.log(Array.isArray(JSON.parse(document.cookies.split('=')[1])));
<pre id="content"></pre>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The setInterval timer is malfunctioning within the render() method of ReactJS

In my React component, I have a countdown timer that starts at 10 seconds. If the backend data is received within this time frame, the timer stops. If not, it will continue counting down to 0 and then refresh the page, repeating the cycle until the data is ...

Sending data to another page in React Native can be achieved by passing the values as parameters

I am currently working on passing values from one page to another using navigation. I have attempted the following code: this.props.navigation.navigate('welcome', {JSON_ListView_Clicked_Item:this.state.email,})) in the parent class where I am s ...

Printing documents from a database using Mongoose version 7.3.1: A comprehensive guide

Currently, with Mongoose 7.3.1, I have inserted some documents into the MongoDB database. However, when I try to log these documents using console.log() by using Fruit.find({}) and outputting it to the console, I get a massive dataset of unwanted objects. ...

The mousedown event handler in Three.js disrupts the focus on the input field

Here is a line of code in threejs: document.addEventListener('mousedown', onDocumentMouseDown, false); This particular code snippet causes the input field to lose focus when clicked. This can be problematic, for instance, when there is a canva ...

Storing Redux state in local storage for persistence within a React application

Recently, I've been experimenting with persisting data to local storage using Redux. My approach involved creating an array of alphabet letters and setting up an event listener to log a random letter each time it's clicked. However, despite succe ...

Are you struggling with Grails - Ajax submission not functioning properly?

Trying to update a div when a form is submitted, but it seems like something is missing. Here's the HTML code: <%@ page contentType="text/html;charset=UTF-8" %> <html> <head> <meta name="layout" content="main" /> ...

Utilizing Nuxt Axios to assign response data to a variable will dynamically modify the content of the

async fetch() { try { console.log(await this.$api.events.all(-1, false)); // <-- Logging the first statement const response = await this.$api.events.all(-1, false); // <-- Assigning the result console.log(response); // <-- Lo ...

Enhancing Security in the apex.server.process Function in Oracle APEX

Once we have disabled a button using client-side JavaScript, our goal is to initiate an Ajax call to create a record in a database table through an On-Demand Process. However, there is a concern that users could bypass this process by making similar calls ...

jquery activating the toggle function to switch between child elements

I'm facing a challenge where I can't use .children() in this scenario, as it won't work since the elements aren't technically children. Here's the snippet of HTML that I'm working with: <p class="l1">A</p> ...

The dojo array implemented a new element, pushing out the old one

The JavaScript code below is supposed to populate the array personNames with objects containing names from an array of persons. However, it incorrectly repeats the same name for each object instead of assigning different names: [{"name":"smith"},{"name":" ...

Utilizing Javascript within a PHP while loop to showcase map markers

Is there a way to display multiple database entries in a loop and show them as markers on a map like this: https://i.stack.imgur.com/SwaGP.png I am struggling with looping through JavaScript in PHP to display multiple markers. Is it possible to achieve t ...

The "body" object cannot be accessed in a post request made from an Express router

I am currently utilizing Express router functions to manage some POST requests. Client.js let data = { endpoint: "Blah Blah"; }; return fetch('/api/get-preferences/', { method: 'POST', headers: { 'Content-Type': & ...

Encountering difficulties in storing array data into MongoDB collection

I am facing an issue with connecting to two different MongoDB instances using different URLs. One URL points to a remote connection string while the other one is for a local MongoDB instance. Initially, I establish a connection to MongoDB using MongoClient ...

Rerendering of a React component occurs upon a change in its state

Previously, my form was functioning flawlessly. However, after making a few modifications to the state variables, the input field now loses focus upon a state change. I am utilizing MUI and everything was working perfectly until this sudden issue arose f ...

Is it possible to prevent the fade out of the image when hovering over the text after hovering over the div or image, causing the text to fade in?

Using React and CSS. I have set up my application to display a faded image on hover, with text that fades in over it. However, I am facing an issue where touching the text with my cursor removes the fade effect. Does anyone have a solution for preventing ...

Encountering a Problem with Chart.js Library During Online Tutorial on YouTube

Currently, I am immersed in a YouTube tutorial that guides me through the process of creating an expense tracker application. However, as I diligently follow the steps outlined in the tutorial, I encounter a hiccup along the way. Instead of witnessing the ...

Is it possible to utilize the router.query feature in a function within Next.js?

Running into a problem with my Next.js page. I'm attempting to utilize the request params in a function, but it keeps coming up as undefined. I've exhausted all my troubleshooting options. I already know that there's no need to include id i ...

What is the best method for looping through a JavaScript object in cases where the value itself is an object?

Updated query. Thanks to @WiktorZychla for sparking my Monday morning thoughts on recursion. The revised code is functioning correctly now. Assuming I have a dummy object structured like this: const dummy = { a: 1, b: 2, c: { d: 3, ...

Node JS promise predicaments

I'm stuck trying to figure out why this function is returning before my message array gets updated with the necessary values. var calculateDistance = function (message, cLongitude, cLatitude, cSessionID) { return new Promise(function (resolve, re ...

The module 'myapp' with the dependency 'chart.js' could not be loaded due to an uncaught error: [$injector:modulerr]

Just starting out with Angular.JS and looking to create a chart using chart.js I've successfully installed chart.js with npm install angular-chart.js --save .state('index.dashboard', { url: "/dashboard", templateUrl ...