I have a cookie named myName
In php, to print the cookie value, I can simply do
<?=$_COOKIE['myName']?>
The shortest I have found in JS is:
<script>
document.write($.cookie('myName'));
</script>
Is there not a better/shorter way to do this? Maybe with JQuery?
I am quite new to JS and moving a site over from PHP for mobile Phonegap Build dev so can't use PHP
If you don't want to use a plugin like jQuery $.cookie, you can do something like this
function getCookie(cookiename) {
var cookiestring = RegExp(""+cookiename+"[^;]+").exec(document.cookie);
return unescape(!!cookiestring ? cookiestring.toString().replace(/^[^=]+./,"") : "");
}
var value = getCookie('myName');
FIDDLE
You can use jQuery Cookie plugin (http://plugins.jquery.com/cookie/) and get cookie just like
$.cookie("myName")
And what you will find very usefull is to use the console while debugging: write in your code:
console.log(document.cookie);
or
console.log($.cookie('myName'));
And see the results in the javascript console of your browser (easiest way: right click in your page, go to the last item which says "inspect element", and in the window that will open, go to the last tab, named "console".)
use a self executing function
<script>
(function(){document.cookie="username=test; expires=Fri, 28 Feb 2014 12:00:00 GMT; path=/";})();
</script>
check out more information on MDN
Related
I have some javascript on my website that loads a modal on a specific page. It uses a cookie to determine whether someone has seen the modal. I need to set an expiry date/time for this but don't know how. I've checked on here for answers but can't see anything that helps me with the code I've got.
Can anyone help? I thought the '365' in the code specified the no. of days for the cookie to expire but it's expiring when the browser session ends.
<script type="text/javascript">
$(document).ready(function() {
if ($.cookie('MyCIEH_popup') == null) {
$('#modalLarge').modal('show');
$.cookie('MyCIEH_popup', '365;');
}
});
</script>
replace $.cookie('MyCIEH_popup', '365;'); with:
$.cookie('MyCIEH_popup', 'value', { expires: 365 });
Note: It's probably a better solution to use native js for that, see here.
I'm using an to call a javascript function, like so:
<a onClick="AddCookie();">Click Here</a>
This is my javascript function, very basic:
function AddCookie(){
Alert ("test"):
}
Whenever the user clicks on "Click Here" I want a cookie created, now I am using ASP in Umbraco which means I can use C# code through HTML so I am creating a cookie like this:
HttpCookie IsDesktopCookie = new HttpCookie("IsDesktopVersion");
IsDesktopCookie.Value = "true";
IsDesktopCookie.Expires = DateTime.Now.AddDays(1d);
Response.Cookies.Add(IsDesktopCookie);
Adding that to my function:
function AddCookie(){
alert("test");
HttpCookie IsDesktopCookie = new HttpCookie("IsDesktopVersion");
IsDesktopCookie.Value = "true";
IsDesktopCookie.Expires = DateTime.Now.AddDays(1d);
Response.Cookies.Add(IsDesktopCookie);
}
However that doesn't work! I also tried adding <% %> around the C# code but it seems to break every time saying function "AddCookie" is not defined.
How do I get this to work?
Even though you can write C# Razor code inside a html page (or rather a cshtml page), you cannot execute C# in the browser just in the same way that you can't execute PHP in the browser even though you can use it within your html pages (or rather .php pages).
Any C# you write within your html template will be executed by the server when the request is made. You cannot interchangeably put C# in a javascript function and expect it to compile to javascript.
If you want to create a cookie on a button click, you can do so with javascript entirely:
function addCookie() {
document.cookie = "name=mycookie; expires=Fri, 23 Feb 2018 09:45:00 UTC; path=/";
}
You're then free to retrieve that cookie via javascript or use your C# code to check for the cookie at request time and render your page content differently on page load if that's what you're hoping to do.
If you need to create cookie in your javascript code then I will suggest you to look at jquery library
https://github.com/carhartl/jquery-cookie
In which you can easily create a cookie
$.cookie('name', 'value');
To read cookie value
$.cookie('name');
function AddCookie()
{
alert("test");
$.post(
{
type: 'POST',
url: '#Url.Action("CreateCookie")',
success: function(result)
{
//cokiee created
},
complete: function() {}
});
You can create or edit cookie like that. In 'CreateCookie' action, write your cookie creation codes
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
Using Javascript & Jquery, I'm creating a cookie on a click event, and then redirecting the user to another page. I'm doing that like this:
<script type="text/javascript">
$(".my-div").click(function() {
document.cookie ="answers=:" + myAnswers + "; path=/; domain=.mydomain.com;";
setTimeout("location.href = '/my-destination-page.php/';", 5000);
});
</script>
When I reach my-destination-page.php, I can see the cookie is set correctly in Google Developer Tools. However, PHP doesn't detect that it's set:
<?php
var_dump($_COOKIE['answers']);
?>
The above returns a big fat NULL.
Any ideas why this is happening?
try to change,
document.cookie ="answers=:" + myAnswers + "; path=/; domain=.mydomain.com;";
to
document.cookie ="answers=:" + myAnswers + "; expires=Thu, 12 Aug 2015 20:47:11 UTC;path=/; domain=.mydomain.com;";
and check
I didn't test your specific code -- but I know building raw cookie strings manually is a finicky, error prone thing. If you get something wrong the cookie processing code on the server (won't recognize your cookies).
Since you're already using jQuery, I'd try using the jQuery cookie plugin. Even if you don't want to deploy with this plugin, you can use it to set your cookie, examine the request headers, and determine where your cookie string is incorrect (or determine that your cookie strings is correct, and that your problem lies elsewhere)
I have set a session in PHP, which is creating a cookie: PHPSESSID...
I can detect this in Chrome & Opera by using document.cookie. However in Forefox, document.cookie also returns cookies set on the page by other domains, e.g. Google Analytics.
In PHP I am setting the sessions like:
session_start();
$_SESSION['source'] = &$ref['source'];
$_SESSION['term'] = &$ref['term'];
session_write_close();
I need to be able to detect if this session is set in Javascript, by locating the cookie. What is the best way to go about this?
At the moment I am just using:
document.cookie.indexOf( 'PHPSESSID' )
which seems like a bit of a botch.
The document.cookie property will return all the cookies. While your indexOf will work, it will break if your cookies actual data contains 'PHPSESSID'. It will also match the following cookie 'MYPHPSESSIDIDIT', as it contains your cookie name.
You could parse the cookies with the following function (not tested):
function getCookieValue(name)
{
// find cookie entry in middle?
var s=document.cookie,
c=s.indexOf("; "+name+"=");
if(c==-1)
{
// no, is it at the start?
c=s.indexOf(name+"=");
if(c!=0) return null;
}
// get length of value
var l=c+name.length+1,
e=s.indexOf(";",l);
// is it at the end?
if(e==-1) e-s.length;
// cut out the value
return s.substring(l,e);
}
Hope this helps
Use this Jquery plugin, it's so cool.
https://github.com/carhartl/jquery-cookie
You can use it like this way:
if($.cookie('PHPSESSID') != undefined){
//PHPSESSID exists
}