Cookie JS, JQuery SET & Remove, Delete

What are Cookies? Cookies are data, stored in small text files, on your computer, today cookie for JS , JQuery.

When a web server has sent a web page to a browser, the connection is shut down, and the server forgets everything about the user. Cookie similar is Session but cookies save data, work on client browser only, Session saving on server not browser.

<script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery.cookie@1.4.1/jquery.cookie.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/moment@2.30.1/moment.min.js"></script>

before using cookie cookie, jquery, moment date module make sure to import!, place to before : </head>

 

Create Cookie JQuery

$.cookie('name_cookie', value, {option});

Remove Cookie JS JQuery

$.removeCookie('name_cookie');

Example use cookie

<div class="col-8">
<button id="del">Delete cookie</button>
</div>

<script type="text/javascript">

$(document).ready(function(){

if (!$.cookie('x')){
// get random value cookie
var time = moment().format("DMY-H_mm_ss/");
var value =time+Math.floor(Math.random() * (999 - 9) + 3);

var date = new Date(); // get time expired
date.setTime(date.getTime() + (5 * 60 * 1000)); // 5 minute

$.cookie('x', value, {expires: date}); // set cookie
console.log('cookie has created');
} else {
console.log('ID_cookie : '+$.cookie('x'));
}

$("#del").click(function () {
// if delete, remove cookie manual
$.removeCookie('x');
});

});

</script>
READ :  PHP Syntax & Komentar / PHP Dasar