Setting and fetching cookie using javascript - javascript

I have tried setting a cookie as:
var cookievalue='ABC';
document.cookie="name=" + cookievalue;
After that, i have tried reading a cookie on a next page. Like
var allcookies = document.cookie;
alert( allcookies );
Now a problem is the alert box comes to be empty. Please help is it possible to set a cookie on page A suppose and read a cookie on a next page B like the above.

Related

document.cookie returns only PHPSESSID=*random number*

I'm trying to get a cookie I have set but all I'm getting is the PHPSESSID.
I set my cookie in a separate PHP page with:
setcookie("username", $sentname, time()+(60*60*24*30),NULL,NULL,NULL,false);
I can then find it through firefox settings.
When I try to access it using JavaScript on a different page I use:
<script>
$(document).ready(function(){
var cookie = document.cookie;
alert(cookie);
});
</script>
which then returns:
PHPSESSID=gvjsgfd8etlbdq43lndni3o0g4
It should return all the cookies, only "username" so far, I have set in a key paired string. I tried using the jquery plugin for cookies and it returned the same thing. I also couldn't find this problem elsewhere online.
Not sure if I should delete the question but one of the related links gave me the answer.
The cookie path must be set to '/' to be accessible from all subdomains. so I changed it too:
setcookie("username", $sentname, time()+(60*60*24*30),'/',NULL,NULL,false);
which gives me:
PHPSESSID=gvjsgfd8etlbdq43lndni3o0g4; username=asdf

Reload page with javascript only one time for load cookies

I have a function that request a data for the user one time. I need reload the page after save these data in a cookie and server read these cookie, but i dont know if these cookie are defined or not. ¿How i reload only one time if i dont have a counter and dont like use parameter? the referrer dont change with reload.
I now have this methot, but i like change for remove parameters:
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [, ""])[1].replace(/\+/g, '%20')) || null
}
if (getURLParameter('reload') != 'true') {
//here have function for load cookie
window.location = window.location.href + '?reload=true';
}
HTTP is a stateless protocol, which mean there is not way - within the protocol - to know the state of a request. For instance : is it the first time it's launched or the second time ?
Usual workarounds are adding a parameter to the request, as you suggests or using a cookie on the browser's side. This is how sessions are implemented in platforms like Java EE or PHP.
Why don't you test for another cookie like 'never been reloaded', if it does not exists : create this cookie and reload the page.
The tricky part is when should you delete the cookie, ie : when does your business logic wants you to reload the page again ? That's up to you to decide.

Why is php not removing cookie set by javascript?

There is post comment box on my site.
Posting comment is handled by javascript, js posts data to php script and php does the db related stuff and shows confirmation only if user is logged in if user isnt logged in then php gives not_loggedin response after receiving it js shows the bootstrap pop over box with link to login page.
So if user is not logged in then the javascript stores the entered comment in cookie so that after logging in user dont have retype the comment. Like this
document.cookie = id + "=" + input_text + "; ";
and after logging in the comment textarea is populated by reading the cookie which has the stored comment text..
everything up to this is working perfect but after inserting the comment in php i am trying to remove the cookie like this .,
setcookie($id, "", time()-3600);
print_r($_COOKIE);
exit('<p class="bg-info">Thank you! Your comment has been posted.</p>');
but its still not removing cookie , when i reload the page , the comment textarea box i populated with the previously enetered comment which is read again from cookie.,
how do i solve this ?
i even tried displaying the cookie in php which is stored by js , lke this
//insert comment in db
//setcookie($id, "", time()-3600);
print_r($_COOKIE);
exit('<p class="bg-info">Thank you! Your comment has been posted.</p>');
but it doesnt shows the cookie which is set by the js, it shows PHPSESSID cookie after posting comment.,
Array
(
[PHPSESSID] => c5rc6c8ggg24edg1v2o8hebb20
)
i am not trying to remove the PHPSESSID cookie.,
i am showing this on page using js . as
post_comment.php is another file in another directory on the same server .
what i am doing wrong ?
In simple words ,
js is setting cookie and php should remove cookie.
----------
update 1 :
i tried setting path while setting cookie in js like this
document.cookie = id + "=" + input_text + "; path=/";
and after posting cookie., now i get this.,
Array
(
[PHPSESSID] => c5rc6c8ggg24edg1v2o8hebb20
[4778] => this is comment
)
my php code is like this .,
//insert comment is db
setcookie($id, "", time()-3600);
printr($_COOKIE);
exit('<p class="bg-info">Thank you! Your comment has been posted.</p>');
but cookie is still there.
update 2 :
this is very strange.,
if i try to set the cookie of the same name in php , one more cookie gets created.
my php code.
setcookie($id, "sdf", time()+36000);
printr($_COOKIE);
exit('<p class="bg-info">Thank you! Your comment has been posted.</p>');
now when i check the broswers cookie manager , i see 2 cookies with the same name .,
but both having different content , the one which was set usng javascript have the comment enetered by user and another cookie which we set using php above , is having content "sdf".
i dont know how is this possible to be having2 cookies with the exact same names. ,
any clues ?
You need to make sure the all the
parameters (except name and time depending on the cookie.) are same while Setting Cookie in Javascript and while Removing Cookie in PHP
Parameters i.e. name,path (value and expire time can be different.)
for eg.
While setting cookie in javascript if you use it like this
document.cookie = id + "=" + input_text + " ; path=/";
you set the path to "/"
then while removing cookie in php you should specifically set like this.
//remove cookie.
setcookie($id, "", time()-36000 , "/");

How to get cookie value with javascript or jquery

I am getting following cookie values on my home page.
vsettings=HiddenNotifications=%2C19%2C;
(referral)|utmcmd=referral|utmcct=/;
ASPSESSIONIDQCSBCCAD=LFLGDKACEGPCPFGBANHFFBMK;
ASPSESSIONIDSASDCCDA=OFEHPJACGHNKICDLFBOCJNNH;
ASPSESSIONIDQCSDDCBC=LGFPBDLCKHLIOLPMCAGJNFIM;
ASPSESSIONIDQCTACBAC=DCIPJDLCNDBEGEIIELCGFMDP;CustomerID;
ASPSESSIONIDSCTCAABD=LHPFFLFDEMIBIENBMGMLFIFP;
ASPSESSIONIDSAQDDDAD=HMCDMLFDFCLJCIBHMEHPNHME; s_cc=true;
__utmc=97358351; CustomerID=755B031ED8C016EC4F90D6F3127E776AE202DEF5BC6EB9F7A9BB19E49323BC3B;
ASPSESSIONIDQCSDBDAC=CFBDJEAAPJJGHMDGOCCHALHC;
ASPSESSIONIDSASCBDAD=FLGJHFAAJAJBICGIMOOJEFFF;Session%5FToken=C8F2A63C3BBA4E39BBF73B83C108D1C6
I want get the value of CustomerID cookie.
Using jquery I wrote this:
$.cookie('CustomerID',{ path:'/'});
But I am not getting the value for cookie - it is showing me blank.
How can I get the CustomerId cookie?
What you did is setting a cookie and not getting a cookie.
try var customerId = $.cookie('CustomerID');
or maybe you are trying to get the cookie from the root path but it's actually lives at a lower path..
Check out where you save the cookie!

How to get cookies value on another page with jQuery?

I have called one PHP page inside an iframe
I have stored some values in cookies. I want to read those cookies values from that page to other page.
I used jQuery to read the cookie.
var value = $.cookie('artname');
'artname' is the cookie name.
But it is displaying null because the cookie path is different. The path is /v/abcfile/frontend/.
But the path for the other cookies on the page i am trying to get is /.
I tried with this:
top.jQuery.cookie('artname');
But it's still showing me the same.
For path ii have tried with:
var value = $.cookie("artname", { path:'/v/vspfiles/frontend/' });
Its still showing me the null value.
How can I get value of cookie?
When you save your cookies, set path to "/". Cookie will be available on all pages
$.cookie('artname', 'value', { path:'/'});
This worked for me:
$.cookie.defaults = { path: '/' };
$.cookie("foo", "value" );

Categories