Submitting cookie in dynamic form jquery - javascript

I am making a dynamic form and submitting it, when user clicks a href tag.
Here is the code
<script>
$(document).ready(function () {
$("#logout").click(function () {
var form = document.createElement('form');
form.setAttribute('action', '${pageContext.request.contextPath}/logout/user');
form.setAttribute('method', 'POST');
document.body.appendChild(form);
form.submit();
});
});
</script>
Issue is that, i have to also submit a cookie which was previously set when user logged in my application. Currently at the back end i am not getting the cookie.
How to submit the cookie as well.

You can then do:
$.cookie("test", 1);
To delete:
$.removeCookie("test");
Additionally, to set a timeout of a certain number of days (10 here) on the cookie:
$.cookie("test", 1, { expires : 10 });
If the expires option is omitted, then the cookie becomes a session cookie, and is deleted when the browser exits.
To cover all the options:
$.cookie("test", 1, {
expires : 10, //expires in 10 days
path : '/', //The value of the path attribute of the cookie
//(default: path of page that created the cookie).
domain : 'jquery.com', //The value of the domain attribute of the cookie
//(default: domain of page that created the cookie).
secure : true //If set to true the secure attribute of the cookie
//will be set and the cookie transmission will
//require a secure protocol (defaults to false).
});

Related

Clearing a cookie via JS and yet PHP still detects it

I'm setting a "SESSION" cookie via JS:
var d = new Date();
d.setTime(d.getTime() + (2*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = cookie.name + "=" + cookie.value +";"+ expires + ";
path="+cookie.path+";domain="+data.shared_domain+";";
Then I'm deleting the cookie by making it expire, via JS:
document.cookie = "SESSION=; expires=Thu, 01 Jan 1971 00:00:01 UTC; path=/;domain="+domain;
After doing this, console.log(document.cookie) will return all other cookies except this one, which is what I would expect.
On the other hand, I am doing session checks via PHP, trying to read the cookie by doing $_COOKIE["SESSION"].
isset($_COOKIE["SESSION"]) will return true, and I can read the old value of the cookie. No matter how many times I refresh the page, it still reads it.
Am I misunderstanding how cookies work? Is there another way to check if a cookie has expired in PHP?
Update:
Yes, the problem is that the cookie has an HttpOnly flag.
So now I'm trying to delete it via PHP. Based on this other question, I do:
setcookie("SESSION", "", time()-3600);
if (isset($_COOKIE['SESSION'])) unset($_COOKIE['SESSION']);
When I'm done, I check that it's gone with a quick var_dump($_COOKIE), and yes, it is nowhere to be seen.
Except that Chrome still sees it (expired in 1969), and when I navigate to another part of the site, checking for that cookie will return a value.
I will add one extra piece of information, in case it makes a difference: This cookie is shared by sub.domain.com and app.sub.domain.com. When I set it, I set it for .domain.com. And I unset it for .domain.com as well.
How can I get rid of that cookie for good?
It's not clear how you're creating the cookie in the first place; I assume using PHP's session handler, but you haven't specified.
Either way, it is likely being generated with cookie security settings that limit access to it from the JavaScript. This setting is called httpOnly and is typically used on session cookies and other similar cookie data that is intended for use only by the server-side code.
If this cookie setting has been set (and any good session handler will have set it), then you simply won't be able to set or unset this cookie from the browser; you will have to do it from your PHP code.
For more info on this topic, see this wikipedia article: https://en.wikipedia.org/wiki/Secure_cookie

converting cookies into sessions without javascript

I want to use a cookie to create a session where it expires when the user closes the browser window. All of the posts online says the way to do so is to remove the expires attribute from the cookie. But I tried to do that and that did not work.
I have the following cookie string:
example=true;path=/
Note that I did not set the expires attribute.
What happens is that the expires attribute gets set to 1 year from now.
Try setting this cookie with expires=0.
session_set_cookie_params($expire, $path, $domain, $secure, true);
// Open
session_set_cookie_params(0, '/', '.example', false, false);
// Locked Down
session_set_cookie_params('o, /forums', 'www.example.com', isset($_SERVER["HTTPS"]), true)

How does one simulate the setting of a cookie by a javascript function in python mechanize?

I am trying to use python mechanize to login into and to step through a web site whose initial page has a warning that one must click on and acknowledge in order to be able to proceed to the login page. Clicking on the link activates a javascript function that sets a cookie and sends you to the login page.
The html for the warning is
<a id='has-seen-warning' class='button' href='/login/'>I Agree</a>
and the javascript that sets the cookie is the following:
<script>
$(function(){
var agreed_to_cookie = 'agreed_to_notice';
$('#has-seen-warning').click(function(){
$.cookie(agreed_to_cookie, 'True', {expires: 365, path:'/', secure: true});
});
});
</script>
Schematically, my python code looks as follows:
import mechanize
br = mechanize.Browser()
url = "https:/blah.blah/login"
# Call login page first time
br.open(url)
# but get request to agree to notice.
# Set the cookie
br.set_cookie("agreed_to_cookie=True; expires=Sunday, 08-Dec-13 23:12:40 GMT")
# call the log in page again
br.open(url)
How should I set the cookie so that it appears that I have read and clicked on the warning?
You've replicated Set-Cookie string wrong. Try this
// TODO: replace expiration date with your own
br.set_cookie("agreed_to_notice=True; path=/; expires=Sunday, 08-Dec-14 23:12:40 GMT; secure")

Set cookie without page refresh

I am showing a jQuery overlay when users first visit a particular page
They have a radio button in the overlay that they can click to say they do not wish to see the notification again
I want to set a cookie that the user doesnt want to see the overlay again
Is it possible to set the cookie without refreshing the page?
I was going to make a ajax call back to the server and then set the cookie in the response headers but I guess they wont get set in an Ajax request/response?
Is it safe / OK to set the cookie purely from javascript? Or is that a bad idea?
any other options?
There is no reason that an AJAX call cannot set a cookie. It is basically just an HTTP request.
AJAX Requests Get And Set Cookies Like Any Other HTTP Request
You may use jQuery Cookie Plugin.
Some example:
function setCookieFilters() {
var $filtersContent = $(".dynamic-filters");
if ($filtersContent.length > 0) {
if ($filtersContent.css("display") == "none") {
$.cookie("isUsingFilters", "true", { expires: 7 });
}
else {
$.cookie("isUsingFilters", "false", { expires: 7 });
}
}
}
you could also just get/set the cookie in plain old javascript:
Create and Store a Cookie
Use this: this shall reload the page.
setcookie($data,$item_data, time()+ (3600));
echo "<script>location.href='index.php'</script>;

onSubmit function sends cookie even without submit

I simply try to set cookie when form is submitted but it seems that the function sets
cookie on every refresh of page
function Sub(){
var exdays="3000";
var value="asdf";
var exdate=new Date();
var c_name="asdf";
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
alert("asdf"); //just for debugging
return true; }
</SCRIPT>
<form id="myform" action="http://localhost" onsubmit="return Sub();">
The cookie will be sent by the browser on each request for the same URL until it is deleted, it expires, or for session cookies, until a new session is created.
You're setting an expiration, so it's not a session cookie. So your browser will send the cookie on each page load to that URL, regardless of whether you clicked something or not.
Try removing the expiration date, clearing your cookie cache, and restarting your browser.
The cookie will not be present until you submit once. Then the cookie will be present until you close your session (restart the browser).
Do you mean the cookie is changed on every reload or that the cookie exists?
I am assuming here that you are using the cookie to send a bit of information to the server along with the form.
Cookies are persistent, and will stick around until they are changed. It might make more sense to have a hidden field in the form, and change the value of that, instead of setting a cookie.

Categories