I’m trying to maintain the position of the vertical scroll bar so user need not to scroll to where they were when the page auto-refresh. This is the first time I’m using JavaScript so I haven’t written anything yet to make the scroll bar function work but tried to test using cookies tutorial on the Internet like simple cookies tutorial to ask for your name and then the page will display our your name on the alert box.
<html>
<head>
<script type="text/javascript">
<!--
function WriteCookie()
{
if( document.myform.customer.value == "" ){
alert("Enter some value!");
return;
}
cookievalue= escape(document.myform.customer.value) + ";";
document.cookie="name=" + cookievalue;
alert("Setting Cookies : " + "name=" + cookievalue );
}
function ReadCookie()
{
var allcookies = document.cookie;
alert("All Cookies : " + allcookies );
// Get all the cookies pairs in an array
cookiearray = allcookies.split(';');
// Now take key value pair out of this array
for(var i=0; i<cookiearray.length; i++){
name = cookiearray[i].split('=')[0];
value = cookiearray[i].split('=')[1];
alert("Key is : " + name + " and Value is : " + value);
}
}
//-->
</script>
</head>
<body>
<form name="myform" action="">
Enter name: <input type="text" name="customer"/>
<input type="button" value="Set Cookie" onclick="WriteCookie();"/>
<input type="button" value="Get Cookie" onclick="ReadCookie()"/>
</form>
</body>
</html>
When I click on “Get Cookie” button, the alert will list out PHPSESID value and some other cookies value that I’ve tested earlier using a different. So I use print_r to display out the $_COOKIE array and discovered the JavaScript cookies are added to PHP’s cookies as well. Is there anyway to create cookies using JavaScript without having to affect PHP’s cookies?
While there are cookies that can be restricted to server side, there are no cookies that can be restricted to client side. You could always namespace the cookie names to avoid conflicts.
If you are targeting modern browsers, you could also make use of localStorage. There are some great questions here regarding how to implement that.