[JS & PHP] How to set cookies in JavaScript and get in PHP

There is the application I built today which required to send data between JavaScript and PHP. Therefore, instead of sending AJAX request everytime data has changed, I decided to set cookies from JS and use PHP to retrieve the cookies when needed.

JavaScript Setup for Cookies

I used the library called JS Cookies: https://github.com/js-cookie/js-cookie. It provides simple interface for storing and getting cookies like this:

Cookies.set('name', 'value');
Cookies.get('name');
Cookies.remove('name');

It also automatically convert array to JSON using JSON.stringify when you store array in cookies, but I noticed this feature after I have already wrote stringify in my code :/

PHP Setup for Cookies

I am using WordPress, but you can use this code on any PHP application.

$test_cookies = json_decode( stripslashes($_COOKIE['name']));
foreach($test_cookies as $key => $value) {
  echo $value->id . ' : ' . $value->name . '<br>';
}

The above code is for array of object with this structure { id: 1, name: 'John' } .

Happy coding and please let me know if you have any question 🙂


Also published on Medium.

Leave a Reply

Your email address will not be published. Required fields are marked *