Hi everyone i want to redirect a user to another page if the cookie is set by clicking the button.
<a href="" onClick="SetCookie('pecCookie','dit is een cookie','-1')"><button type="button" name="accept" class="btn btn-success">Button Text</button>
<script>
function SetCookie(c_name,value,expiredays)
{
var exdate=new Date()
exdate.setDate(exdate.getDate()+365)
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+exdate.toGMTString()) +
("; path=/")
location.reload()
}
if
</script>
Works and i also got the if statement in php but i want it in javascript because of wordpress issues. In php it would look like this.
<?php
$cookie_name = "anyname";
$cookie_value = "anycontent";
If (isset($_COOKIE[$cookie_name])) {
// action if cookie is set
}
?>
i can't seem to figure it out in javascript, and i also looked around on the web
After doing this:
<a href="" onClick="SetCookie('pecCookie','dit is een cookie','-1')"><button type="button" name="accept" class="btn btn-success">Button Text</button>
<script>
function SetCookie(c_name,value,expiredays) {
var exdate=new Date()
exdate.setDate(exdate.getDate()+365)
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+exdate.toGMTString()) +
("; path=/")
location.reload()
}
mycookieValue = getCookie("pecCookie")
if(mycookieValue) {
window.location = "193.91.113.21/downloads/";
}
function getCookie(c_name) {
var re = new RegExp(c_name + "=([^;]+)");
var value = re.exec(document.cookie);
return (value != null) ? unescape(value[1]) : null;
}
</script>
it keeps going to the redirect even without the cookie
Here is a function for get the cookie value in javascript.
mycookieValue = getCookie("mycookieName")
if(mycookieValue)
{
//Your code here
}
function getCookie(name)
{
var re = new RegExp(name + "=([^;]+)");
var value = re.exec(document.cookie);
return (value != null) ? unescape(value[1]) : null;
}
I will suggest you use jQuery cookie.js library. You can download it from here.. https://github.com/carhartl/jquery-cookie
Example:
//Set Cookie
$.cookie('userName', 'John');
//Read Cookie Value
var username= $.cookie('userName');
console.log(username);
//Remove a cookie
$.removeCookie('username');
//Cookie is removed then above line will return true
//Check cookie in if else
if(username){
console.log(username);
}
// or you can do this also
if(username=='John'){
console.log('User Name is '+username);
}
Hope this will help you.
Related
I have an application that needs to pop a URL based on a Query String sent to it. Unfortunately, we can't insert any javascript into the application itself, but we can insert an iFrame that loads a page running javascript. There is a bug in the application where it loads the content in the iFrame twice within a couple seconds, which results in the URL popping twice.
To resolve this, I decided to set a cookie with an expiration. Before popping, I would check to see if the cookie exists, and if it does, prevent the pop from happening.
Unfortunately, my cookie is not being set. I've read a few threads about Javascript cookies trying to figure this out. The first thing I found is Chrome does not accept cookies from local files, so I set up an IIS server to host the page.
However, the cookie still is not being set. I read this page to make sure my code was correct, and as far as I can tell, it should be correct.
The code for my page is below. Any help would be greatly appreciated.
<html>
<head>
<script type="text/javascript">
var isPopped;
function myFunction() {
alert("Hello! I am an alert box!");
}
function checkCookie() {
var user=getCookie("username");
if (user != "") {
alert("Welcome again " + user);
} else {
user = prompt("Please enter your name:","");
if (user != "" && user != null) {
setCookie("username", user, 30);
}
}
}
function pop() {
var queryString = location.search.substring(1); //Get Query String from URL of iFrame source. The substring(1) strips off the ? and only takes the first substring. This can be modified to take more and the resulting string can be edited with Regular Expressions if more flexibility is required.
var urlToPop = "https://www.google.com/#" + queryString //Set URL to pop.
var recentVisitTrue=getCookie("visitRecent");
if (recentVisitTrue != "") {
isPopped = 1;
} else {
window.open(urlToPop,"_blank");
setCookie("visitRecent", "true");
}
}
function setCookie(cName,cValue) {
var date = new Date();
date.setTime(d.getTime() + 8000000);
var expires = "; expires=" + date.toGMTString();
document.cookie = cName + "=" + cValue + expires + ";path=/";
}
function getCookie(cName) {
var name = cName + "=";
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);
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
</script>
</head>
<body onload="pop();">
v0.32
</body>
</html>
Thanks!
I have this url http://localhost:1234/pag1
I want to be like below when I click on the div:
http://localhost:1234/pag1?fare=standar
and I have an onclick event function:
<div id="" onclick="addUrl();"> </div>
And the js code:
<script type="text/javascript">
function addUrl() {
var url = window.location.href;
window.location.hash = '?fare=standar';
};
</script>
This give me this result:
http://localhost:1234/pag1#?fare=standar
And I don't Know how to remove the (#). I only need to add the parameter to the url, without refresh the page.
Suggest me! Thank's.
Use window.history.pushState( {} , '', '?fare=standar' );
This should update the url without refresh.
You can also do a bit of reseach on pushState as the implementation can differ.
window.location.hash always put "#" in url
you can use to push paramter in url by using this function
function setGetParameter(paramName, paramValue)
{
var url = window.location.href;
if (url.indexOf(paramName + "=") >= 0)
{
var prefix = url.substring(0, url.indexOf(paramName));
var suffix = url.substring(url.indexOf(paramName));
suffix = suffix.substring(suffix.indexOf("=") + 1);
suffix = (suffix.indexOf("&") >= 0) ? suffix.substring(suffix.indexOf("&")) : "";
url = prefix + paramName + "=" + paramValue + suffix;
}
else
{
if (url.indexOf("?") < 0)
url += "?" + paramName + "=" + paramValue;
else
url += "&" + paramName + "=" + paramValue;
}
window.location.href = url;
}
i hope this will helpful to you
Try this
HTML
<div onclick="addUrl()"> </div>
Javascript
<script type="text/javascript">
function addUrl() {
var url = window.history.pushState( {} , '', '?fare=standar' );
</script>
Quick Explanation : When user clicks on div, URL will update without refreshing the page.
Hope this will work for you,
thank you :-).
Try this
var myURL = document.location;
document.location = myURL + "?a=parameter";
Or
location.hash = 'a=parameter'
Or without reloading the page
window.history.pushState("object or string", "Title", "new url");
Or without reloading the page
window.history.replaceState(null, null, "/another-new-url");
Why dont you use jQuery? I prepared sample like here in JsFiddle:
$("#clickableDiv").click(function(){
var url = "http://localhost:1234/pag1";
var parameter = "fare=standar";
$("#AppendUrl").text(url+ "?" + parameter);
});
How can I turn this into a session cookie?
I know I would start by getting rid of the exipredays, but when I set the expiredays to 0 the message cbox displays everytime your refresh the page and I could see that getting annoying..
<p align="center">DISCLAIMER GOES HERE</p>
<script type="text/javascript" language="javascript">
var agreement = GetCookie();
// checks for cookie and displays disclaimer alert if new user
if(agreement=="")
{
var decision = confirm("DISCLAIMER: GOES HERE \n\nClick Ok if you agree to the disclaimer or click Cancel to close this window. \n");
if(decision == true)
{
// writes a cookie
var expiredays = 7;
var exdate=new Date()
exdate.setDate(exdate.getDate()+expiredays)
document.cookie="PartnerAgreement"+ "=" +escape("Agree To Disclaimer")+
((expiredays==null) ? "" : "; expires="+exdate.toGMTString())
}
else
{
// redirect
window.location = "/_layouts/signout.aspx";
// or close the browser window
//window.opener='x';
//window.close();
}
}
// gets the Cookie if it exists
function GetCookie()
{
if (document.cookie.length>0)
{
c_name = "PartnerAgreement";
c_start=document.cookie.indexOf(c_name + "=")
if (c_start!=-1)
{
c_start=c_start + c_name.length+1
c_end=document.cookie.indexOf(";",c_start)
if (c_end==-1) c_end=document.cookie.length
return agreement = unescape(document.cookie.substring(c_start,c_end))
}
}
return "";
}
Your code says:
((expiredays==null) ? "" : "; expires="+exdate.toGMTString())
0 is not null (0 is "immediately"). Set expiredays to null.
I'm trying to do a demo test on javascript cookie. Please find the code below which I wrote for testing.
<html>
<head>
<script type='text/javascript' >
function setcookie()
{
alert("check if cookie avail:" +document.cookie.split(';'));
var dt=new Date();
document.cookie='name=test';
document.cookie='expires='+dt.toUTCString()+';'
alert("now cookie val:" +document.cookie.split(';'));
dt.setDate(dt.getDate()-1);
document.cookie = "expires=" + dt.toUTCString() + ";"
alert("after deletion cookie val:" + document.cookie.split(';'));
}
</script>
</head>
<body>
<input id='txt' onchange='setcookie()' />
</body>
</html>
The code will work as,
Initally, this will display the cookie which is present already in that browser, then I try to set a cookie as 'name=test' with 1day expire time. Using alert I can see the value set in that cookie. In the next line, I try to delete cookie by setting expire date to current date-1. If I use alert to print the cookie value, cookie is displayed with expire date as currentdate-1.
My questions is,
In Mozilla, If I refresh the browser and try to do the same step then the first alert displays the cookie value with expire time as currentdate-1. Why Im getting cookie value even if i delete at the last line of my script. However, once I close the browser the cookie value is empty. Why it is so?
In chrome, If I run the same piece of code, neither of the cookie is set. Why Im not able to set cookie in chrome browsers.
Please tel me why such difference occuring across browsers.
This is not setting the expiry
document.cookie='name=test';
document.cookie='expires='+dt.toUTCString()+';'
this is
document.cookie='name=test; expires='+dt.toUTCString()+';'
The best is to take well tested cookie code and use that
Try this one or use a jQuery plugin if you use jQuery
// cookie.js file
var daysToKeep = 14; // default cookie life...
var today = new Date();
var expiryDate = new Date(today.getTime() + (daysToKeep * 86400000));
/* Cookie functions originally by Bill Dortsch */
function setCookie (name,value,expires,path,theDomain,secure) {
value = escape(value);
var theCookie = name + "=" + value +
((expires) ? "; expires=" + expires.toGMTString() : "") +
((path) ? "; path=" + path : "") +
((theDomain) ? "; domain=" + theDomain : "") +
((secure) ? "; secure" : "");
document.cookie = theCookie;
}
function getCookie(Name) {
var search = Name + "="
if (document.cookie.length > 0) { // if there are any cookies
var offset = document.cookie.indexOf(search)
if (offset != -1) { // if cookie exists
offset += search.length
// set index of beginning of value
var end = document.cookie.indexOf(";", offset)
// set index of end of cookie value
if (end == -1) end = document.cookie.length
return unescape(document.cookie.substring(offset, end))
}
}
}
function delCookie(name,path,domain) {
if (getCookie(name)) document.cookie = name + "=" +
((path) ? ";path=" + path : "") +
((domain) ? ";domain=" + domain : "") +
";expires=Thu, 01-Jan-70 00:00:01 GMT";
}
I am trying to redirect English browsers to xyz.com/?lang=en while letting Swedish ones stay on xyz.com
I have been trying :
var type=navigator.appName
if (type=="Netscape")
var lang = navigator.language
else
var lang = navigator.userLanguage
//cut down to first 2 chars of country code
var lang = lang.substr(0,2)
// Swedish
if (lang == "sv")
window.location.replace('????')
// if none of above (default to English or any other)
else
window.location.replace('xyz.com/?lang=en')
</script>
But I don't know how to write the Swedish URL since it's not a redirection as the default language is swedish... writing the xyz.com gets me into a redirection loop
if ($_REQUEST["lang"] == "en")
{
echo '<div class="langlight">Svenska</div>';
}
else
{
echo '<div class="langbold">Svenska</div>';
}
if ($_REQUEST["lang"] == "en")
{
echo '<div class="langbold">English</div>';
}
else
{
echo '<div class="langlight">English</div>';
}
enter code here
if (lang !== "sv") {
window.location.replace(window.location.href + '?lang=en');
}
You are always checking the language from the navigator.
This way everytime the page loads it will try to reload the page with the altered or not url.
You need to place a condition where it will not reload the page..
That should be when there is a URL parameter passed.
So check for the querystring as well and override the default if a value exists in the url.
<script type="text/javascript">
(function(undefined){
var queryString = {},
search = window.location.search.substring(1), // read the current querystring
searchItems = search.length?search.split('&'):[]; // and split it at the different params if any exist
for(var i = 0, len = searchItems.length; i < len; i++){ // for each parameter passed
var parts = searchItems[i].split('='); // split the key/value pair
queryString[parts[0].toLowerCase()] = parts[1]; // and store it to our queryString variable
}
if (queryString.lang === undefined){ // if there is no lang parameter passed do your checking otherwise skip this step completely and use the url lang parameter.
var type=navigator.appName, lang = '';
if (type=="Netscape") {
lang = navigator.language.substr(0,2);
} else {
lang = navigator.userLanguage.substr(0,2);
}
if (lang != "sv"){
if (searchItems.length){
window.location.replace(window.location.href + '&lang=en');
} else {
window.location.replace(window.location.href + '?lang=en');
}
}
}
}());
</script>
Notice: Although, as #missingno mentions in his comment to your question, this is best handled server-side than client-side.