When running my web page the cookies are not being created I have been using IE as I know that chrome does not load cookies on local web pages.
I am loading the JS as
<script language="javascript" src="script.js" type="text/javascript"></script>
the script to set the cookies which is in the script.js file is
function SetCookie(name,val) {
document.cookie = name + "=" + val + ';';
}
and in my file for the main page I have set the cookie as shown
SetCookie('July',July);
When I run the code the cookie is undefined.
The simplest way to create a cookie is to assign a string value to the document.cookie object
document.cookie = "key1=value1;key2=value2;expires=date";
So, either July has to be a variable or you'll have to pass it as a string.
var July = 'July';
SetCookie('July', July);
OR
SetCookie('July', 'July');
These are my cookies:
My cookies
I'm running my website from my own computer using a WAMP server. I access my main page from http://127.0.0.1/Zulaijen/, and this is the javascript funcion to set the cookies (User and Session):
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "; expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + expires;
}
When I read them using javascript, it works fine. I get my session. Then I go to another PHP page named 'uploader.php' with this code:
if(!isset($_COOKIE['TestCookie']))
setcookie("TestCookie", "Hello World!", time()+3600);
print_r($_COOKIE);
echo("Session: " . $_COOKIE['Session'] . "<br/>User: " . $_COOKIE['User'] . "<br/>");
And the result is:
Array ( [TestCookie] => Hello World! )
Notice: Undefined index: Session in D:\wamp\www\Zulaijen\uploader.php
on line 30
Notice: Undefined index: User in D:\wamp\www\Zulaijen\uploader.php on line 30
Which means my PHP code is not reading the cookies I set with javascript. It only reads the one I set with my PHP code (TestCookie). And I don't understand why. They are within the same domain and the same path.
You should try setting cookie path. Could be that the cookie paths for PHP and JavaScript isn't matching, hence the cookie will not be shared between the two.
JavaScript cookie path:
How do I set path while saving a cookie value in JavaScript?
PHP coookie path (see path section):
http://php.net/manual/en/function.setcookie.php
I finally found out what was causing the problem (by accident). It's very confusing, but it has a very simple solution.
In order to read the cookies from PHP, you must read them from the very beginning of the file.
Doing this:
<?php print_r($_COOKIE); ?>
At the very beginning of the file (before any HTML code) prints every cookie I set correctly as it should. Even if you set them from PHP, if you don't do it from the very beginning of the file you won't be able to get them.
The reason why I was able to read the one I was setting with PHP was simply because I was setting it right before reading it, or so it seems.
Is there a way to update the URL programatically without reloading the page?
EDIT: I added something in the title in post .I just want to make it clear that I don't want to reload the page
Yes and no. All the common web browsers has a security measure to prevent that. The goal is to prevent people from creating replicas of websites, change the URL to make it look correct, and then be able to trick people and get their info.
However, some HTML5 compatible web browsers has implemented an History API that can be used for something similar to what you want:
if (history.pushState) {
var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?myNewUrlQuery=1';
window.history.pushState({path:newurl},'',newurl);
}
I tested, and it worked fine. It does not reload the page, but it only allows you to change the URL query. You would not be able to change the protocol or the host values.
For more information:
http://diveintohtml5.info/history.html
https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history
Yes - document.location = "http://my.new.url.com"
You can also retrieve it the same way eg.
var myURL = document.location;
document.location = myURL + "?a=parameter";
The location object has a number of useful properties too:
hash Returns the anchor portion of a URL
host Returns the hostname and port of a URL
hostname Returns the hostname of a URL
href Returns the entire URL
pathname Returns the path name of a URL
port Returns the port number the server uses for a URL
protocol Returns the protocol of a URL
search Returns the query portion of a URL
EDIT:
Setting the hash of the document.location shouldn't reload the page, just alter where on the page the focus is. So updating to #myId will scroll to the element with id="myId". If the id doesn't exist I believe nothing will happen? (Need to confirm on various browsers though)
EDIT2: To make it clear, not just in a comment:
You can't update the whole URL with javascript without changing the page, this is a security restriction. Otherwise you could click on a link to a random page, crafted to look like gmail, and instantly change the URL to www.gmail.com and steal people's login details.
You can change the part after the domain on some browsers to cope with AJAX style things, but that's already been linked to by Osiris. What's more, you probably shouldn't do this, even if you could. The URL tells the user where he/she is on your site. If you change it without changing the page contents, it's becomes a little confusing.
You can use :
window.history.pushState('obj', 'newtitle', newUrlWithQueryString)
Use
window.history.replaceState({}, document.title, updatedUri);
To update Url without reloading the page
var url = window.location.href;
var urlParts = url.split('?');
if (urlParts.length > 0) {
var baseUrl = urlParts[0];
var queryString = urlParts[1];
//update queryString in here...I have added a new string at the end in this example
var updatedQueryString = queryString + 'this_is_the_new_url'
var updatedUri = baseUrl + '?' + updatedQueryString;
window.history.replaceState({}, document.title, updatedUri);
}
To remove Query string without reloading the page
var url = window.location.href;
if (url.indexOf("?") > 0) {
var updatedUri = url.substring(0, url.indexOf("?"));
window.history.replaceState({}, document.title, updatedUri);
}
Define a new URL object, assign it the current url, append your parameter(s) to that URL object and finally push it to your browsers state.
var url = new URL(window.location.href);
//var url = new URL(window.location.origin + window.location.pathname) <- flush existing parameters
url.searchParams.append("order", orderId);
window.history.pushState(null, null, url);
Yes
document.location is the normal way.
However document.location is effectively the same as window.location, except for window.location is a bit more supported in older browsers so may be the prefferable choice.
Check out this thread on SO for more info:
What's the difference between window.location and document.location in JavaScript?
Prefix URL changes with a hashtag to avoid a redirect.
This redirects
location.href += '&test='true';
This doesn't redirect
location.href += '#&test='true';
Plain javascript: document.location = 'http://www.google.com';
This will cause a browser refresh though - consider using hashes if you're in need of having the URL updated to implement some kind of browsing history without reloading the page. You might want to look into jQuery.hashchange if this is the case.
You'll need to be more specific. What do you mean by 'update the URL'? It could mean automatically navigating to a different page, which is certainly possible.
If you want to just update the contents of the address bar without reloading the page, see Modify the URL without reloading the page
Yes - document.location.hash for queries
I have a website on which I dynamically create Javascript code using ASP.NET handler in which I should add the referrer to a database.
I want to get referrer of referrer like so:
website1
website2 (where I create pixel to another site)
website3 (where pixel is located)
I don't have code access to website1, on website2 I can only assign JavaScript.
If I get referrer in current application state I get website2.
Is there a way to get website1 as referrer?
You can pass this value along: document.referrer.
That expression would need to be evaluated on website 2, not on website 3.
So:
// website2.html
<img src="website3.com/pxl.gif" id="pxl" />
<script>
document.getElementById('pxl').src += '?ref=' + encodeURIComponent(document.referrer);
</script>
The request to website3 will then include the referrer.
It is impossible to get the referrer of website2 on website3 directly. However, since you can use javascript on website2, you could get the referrer (document.referrer) and add it to the url of the pixel you get. For example:
var referer = document.referrer;
var pixelUrl = 'http://website3/pixel?referrer=' + escape(referrer);
// create pixel...
Hope that helps
Seems that document.referrer doesn't work in many instances.
Use the complete window.frames.top.document.referrer instead.
I have a local host called "myproject". When i try to set a cookie for resource "myproject/someresource" like this:
document.cookie = "mycookie=somevalue; path=/someresource";
IE does not set this cookie. But it does if i do not use path parameter:
document.cookie = "mycookie=somevalue";
What am i doing wrong?
according http://forum.de.selfhtml.org/archiv/2009/7/t189018/ the site must be within the specifed path. So I think you have to add a slash at the last position and you site must be in "http://mydomain.com/somesource/filename.datatype"