How to use Cookies to store information In Javascript
Client Side: Use Cookie to store the information, which is then requested in the PHP page. A cookie named gfg is created in the code below and the value w3wiki is stored. While creating a cookie, an expire time should also be specified, which is 10 days for this case.
// Creating a cookie after the document is ready
$(document).ready(function () {
createCookie("gfg", "w3wiki", "10");
});
// Function to create the cookie
function createCookie(name, value, days) {
let expires;
if (days) {
let date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
else {
expires = "";
}
document.cookie = escape(name) + "=" +
escape(value) + expires + "; path=/";
}
Server Side(PHP): On the server side, we request for the cookie by specifying the name gfg and extract the data to display it on the screen.
<?php
echo $_COOKIE["gfg"];
?>
Output:
How to pass JavaScript variables to PHP ?
JavaScript is the client side and PHP is the server-side script language. The way to pass a JavaScript variable to PHP is through a request.
Below are the methods to pass JavaScript variables to PHP:
Table of Content
- Using GET/POST method
- Using Cookies to store information
- Using AJAX