I don't know how to delete a cookie. I want is when I submit a form. The cookie is also delete. I try the delete_cookie("name") but is not working. I think because the cookie I created by javascript. Please check my code to fix this problem.
This is my sample text field:
<input name="cargo_no" type="text" class="validate[required]" id="cargonumber" onchange="setCookie('cargonumberC', this.value, 365);"/>
and this is the javascript
function setCookie(cookieName, cookieValue, nDays) {
var today = new Date();
var expire = new Date();
if (!nDays)
nDays=1;
expire.setTime(today.getTime() + 3600000*24*nDays);
document.cookie = cookieName+"="+escape(cookieValue) + ";expires="+expire.toGMTString();
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
document.addEventListener('DOMContentLoaded', function() {
var themeSelect = document.getElementById('cargonumber');
var selectedTheme = readCookie('cargonumberC');
if (selectedTheme) {
themeSelect.value = selectedTheme;
}
});
Using Codeigniter, put it inside the save method of your controller:
Try:
delete_cookie('name', $domain, $path);
Details on official documentation
You can delete cookie from CodeIgniter. Use cookie helper like
$this->load->helper('cookie');
delete_cookie("name");
To delete a cookie use:
helper('cookie');
delete_cookie('remember_me');
You can't delete a cookie. The browser (or the user) has the delete the cookie(s). But, you can make the browser auto-remove the cookie by setting the expiration of the cookie to a date in the past. Here's a JavaScript example.
function deleteCookie(cookieName, cookieValue) {
document.cookie = cookieName+"="+escape(cookieValue) + ";expires=Thu, 01 Jan 1970 00:00:01 GMT;";
}
Related
Though I have set the cookie using setcookie, why does it skip to the else part during the first time of execution/ first visit?
<?php
setcookie("dan", "Sony", time()+60);
if(isset($_COOKIE['dan']))
{
echo "Set";
}
else
{
echo "Not yet!";
}
?>
P.S: I know it is a naive question and gets downvoted but I don't find a better forum than StackOverflow.
setcookie() merely arranges for the HTML headers emitted by the PHP script to contain the necessary "Set-Cookie:" header. The browser responds by storing the cookie and then regurgitating it on the next request to the site.
setcookie() does not set any variables inside the currently-executing script, which is why you're not seeing anything the first time through.
You can't get value from $_COOKIE in the same request you do setcookie, you could get it begin from the next request.
The first time you only tell the browser to set the cookie, at the time, there is no cookie data in the request header (which could get from $_COOKIE).
Set your cookies with javascript.
function createCookie(name,days,value) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
} else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) { //cookie reader function
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) { //cookie eraser function
createCookie(name,"",-1);
}
createCookie("test", 1, 1);
var mycookie= readCookie("test");
alert(mycookie);
I have made a grid like google to show images and it get loaded on scroll down.
On history back click I want to show the loaded images again.
That is why, On each scroll down I have stored the last loaded page no. in cookie. But an issue come out when I load the same grid page in two tabs in same browser.
Is there any way to create cookies for each tab separately.
I have used following code to create and erase cookies.
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
//var text = document.getElementsByTagName("title")[0].innerHTML;
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
Since cookies are 'domain' wide, they aren't tab or window specific.
Also, it sounds like what your looking for is 'pushState' - which is part of HTML5.
Some useful resources:
-http://diveintohtml5.info/history.html
-https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history
Also a polyfil available here:
-https://github.com/browserstate/history.js/
hope this helps!
I've set a cookie using PHP,
setcookie("redirect", $this->currentPage(), time() + 31536000);
but I want to retrieve the value of this cookie using javascript when a certain link is clicked. How can I do that?
Yes its possible.
Try this to read cookie:
function getCookie(c_name) {
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++) {
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==c_name){
return unescape(y);
}
}
}
// get cookie foo
var foo = getCookie('foo');
Try this to set a cookie:
/**
* Sets a cookie
*/
function setCookie(c_name,value,exdays) {
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
// set a cookie 'foo=bar' for 3 days
setCookie('foo', 'bar', 3);
Cookies are not PHP specific they are browser specific and they can be placed both from PHP and Javascript. For an easy solution, you can look into jQuery's Cookie plugin
Here's another take that attempts to be easier to understand.
Also, since cookies are encoded (both keys and values), you will want to decode them both.
var getCookie = function(name) {
var thisCookie,
keyValuePair,
key,
value,
cookies = document.cookie.split('; ') ;
for ( var i=0 ; i<cookies.length ; i++ ) {
thisCookie = cookies[i] ;
keyValuePair = thisCookie.split('=') ;
key = decodeURIComponent(keyValuePair[0]) ;
if ( key === name ) {
value = keyValuePair[1] ;
return (value != null) ? decodeURIComponent(value) : null;
}
}
}
Regarding the part about getting the cookie on a link click, you would call this function in an event handler.
Let's assume that you know how to get the link in question in JavaScript. Here's one way to get the first link in the document:
var link = document.querySelector('A') ;
In any case, once you have your link, here is how to get the value when the link is clicked:
var getCookieOnLinkClick = function() {
var cookieValue = getCookie('cookieName') ;
console.log('Cookie value is ', cookieValue) ;
}
link.addEventListener('click', getCookieOnLinkClick) ;
(Of course, most links will load a new page, so you won't have much time to do anything with the cookie value once you get it.)
Wrong concept. Cookies are stored in browsers. PHP gets/sets browser cookies through HTTP requests and responses. So both PHP and browser JS can manipulate the same cookies.
function setCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
$(document).ready(function(){
alert(getCookie('foo'));
setCookie('foo','test'); //just setting a cookie on page load
$('#bing').click(function(){
$('#frm1').submit();
});
});
HTML side(foo.phtml)
Go
<form id="frm1" method="POST" action="/somecontroller/someaction">
<input type="hidden" name="foo_post" value="this is from post" />
</form>
//server side
public function someactionAction(){
$_COOKIE['foo'] = $this->_request->getPost('foo_post');
$this->_redirect('/somecontroller/foo');
}
My problem is on the very first load of a page the alert returns null since cookie is not set and if i refresh again,ill get an alert "test" but if i click on the anchor tag a form submit will occur and the cookie value is rewritten as "this is from post",so obviously after the action back to the page ill get an alert of "this is from post" ,BUT im still getting an alert "test" ,The cookie value is not getting rewritten
In my mozilla cookie console there are two cookies with the name foo with values "test" and "this is from post"
"there are two cookies with the name foo"
If the name is identical, the domains must be different. Set both cookies using the same domain. Be aware that example.net is different from www.example.net or .example.net.
I am using this code in my js file for redirect
setTimeout('top.location=\'http://google.com/?123\';', 1000);
Problem is my js file execute many time but i want to add some cookie code in js file so that my visitor dont redirect again and again. so what will be cookie code which execute this js file only once unless i change cookie manually
Create your code with this function in mind, using these steps in order. You can check your js reference for how to do each of these steps. I hope this points you in the right direction.
Check for an existing cookie.
If you find the cookie, do not redirect, otherwise, redirect. (This is where your existing line would come in.)
Set a cookie with a timeout value based on how often you want them to redirect.
Not tested
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
if(readCookie('redirected')!=true)
{
createCookie('redirected',true,0); // cookie will be trashed after the browser closed.
setTimeout('top.location=\'http://google.com/?123\';', 1000);
}
Read here.