Setting Multiple Cookies with Javascript - javascript

I created a simple page that lets you make cookies and displays them by appending them to a text area. My understanding is that you can create as many cookies as you want simply by calling
document.cookie = ...
However, when I print out my cookies, only 3 of them are ever displayed. It also appears that I'm not appending the cookies to the text area properly, because these values never change.
To test if this was a problem with the cookie creation, I used an alert popup box to notify the user when their new cookie is created. This shows me that the cookies ARE being created. So, I don't know why I can only see three of the cookies in the display.
Here is the code:
EDIT: code removed because answer is closed.
How can I fix this so that all the cookies created are appended to the text area? Thanks.

When you set a cookie via document.cookie you provide a key\value pair in the form key=value.
In your code you are always passing a key of "name" so rather then creating a new cookie you're just updating the same cookie every time. You need to find a way to generate a unique identifier to use as the key for each new cookie (perhaps a count will do)
Also you shouldn't need to append the value from document.cookie to the text as document.cookie will return the values for all cookies so you can just set the value of document.cookie to the value of you text area.
More info on document.cookie

Related

how to pop up a Notice Span when user just log in (but not just refresh to the home page)?

I do not know how to detect it is the first time that user login the web.
I thought i should write a pop-up span on the jsp that user firstly saw when he login.but the issue is then he refresh the page,the notic will show again,that is ridiculous.
I need detect if it is first login means to detect if the user JUST LOGIN or NOT REFRESH the page
how and where shall I detect if it is the first time user login ? and then i can make mind if the notice span pop up.
and I think it should use cookies or session,but which one should i use?
Maintain a field in database table that check if it is first login than show a popup and after that change the value of that field so that Popup do not appear next time.
Ex:
if($data['first_login'] == 1)
{
// show popup
}
If you want to show it only to the new user (the time user registers) you can use a table column in database where you can use it to check if the user if logging in for the first time (e.g firtsLogin the column name = 1 ). If he is logging in for the first time you show the pop-up and change the value of the field to 0.
Otherwise if you want to show to users that are logged in to a specific device for the first time you should use cookies.
I suppose that you want to detect the user logging in to your web-site the first time. There are multiple ways that you can do it depending on your desire to spend additional time writing the code, the location of your logging-in logic (client or server side), security that you want to have while proving your users with login functionality. In all cases - you would have to store the data whether the user has logged in for the first time. I think you are seeking a fast solution that will work without a big care for privacy or security as working with client-side cookies isn't the safest way to store data. The alternatives to cookies are web tokens, url query string, server-side sessions and data-base (RDBMS) storage.
Storing and retrieving the data on the client-side using COOKIES. They are the pieces stored in the user's web browser. Cookies were created to help servers remember the data about the user next time he enters the web-site. The most common usages are: to store location (if accepted by user), web-site locale (language in which the user was browsing the site), products added to cart, etc. Following that approach you can create cookie after the user has logged in to your web-site as follows:
This should be run by your JavaScript.
document.cookie = "firstLogin=true";
After having done that, you would have to add JavaScript logic that will hook-up to user's/client's COOKIE data and read up whether he has logged in the first time before.
This would probably look like a simple JavaScript cookie look-up.
var cookieData = document.cookie;
This will return all of your user's cookies that has been previously stored when he visited your web-site. It will return it as a string concatenated with "; ". If we had previously stored only one cookie, we would get firstLogin=true;
In case if you have multiple cookies set before, you would have to parse the cookie string and extract the data either imperatively by plain procedural JavaScript code or by writing the function which will be able to do that repeatedly. Detailed examples of writing such functions could be found here.

How Can I Turn a Query String Parameter into a Cookie that then Sets an Attribute?

Been completely stumped by this but it should be easy. Basically I need a script that
1) Parses a URL for query string ?code=X190 (or any other code value).
2) If present creates a cookie with that attribute/value = so creates MyCookie with value X190 in this case.
3) As the User navigates the site, every page checks for MyCookie and if it finds it, it inserts X190 into the value attribute any form inputs of that page of class "xcode-field".
Right now I'm using document.getElementById("xcode-field").setAttribute("value","X190"); for some dynamic insertions, but I need this to work on a class instead of an ID as there will be multiple forms per page in some cases.
UPDATE: Following the recommendation below I tried this using localStorage instead of cookies, got much further but still having issues saving the data: HTML5 Local Storage item not being saved correclty

How to retain textbox values after navigating to other page?

I have a page(say register page) with text boxes in it. After entering values in them, if I navigate to other to page by using back and forward buttons in the browser and come back to the register page again. I want the entered text box values to be shown. Is there any way to do that. Hope somebody could help. Thanks in advance...
saving to local storage is a bit dangerous, because anyone can go to console and type:
window.localStorage to see the saved values, for ALL USERS of the domain.
for example, on this page of SO right now, the localstorage contains this :
Storage {login-prefs: "{"provider":"google","oauth_version":"","oauth_server":"","username":""}", se:fkey: "c6f10e10979159fee3220954ec846d68,1387300621", wb:isparticipating: "{"1106914":{"t":1387805621703,"v":false}}"}
assuming that the textbox values do not contain personal information,
you will still need to address issue of multiple users on same machine.
one solution will be to use the user ID as a key, the value as a json representation of textboxId : value
example:
on window.befreunload event, strore all the textbox values under a key containing user ID:
localStorage.setItem( 'user_123_form-values' , JSON.stringify( [{ txbox1: 'some text' }, { txbox2: 'some other text' }]) );
to get values:
JSON.parse(localStorage['user_123_form-values'])
here is a fiddle to demonstrate the local storage approach, though if the data needs to be secure,
you will need to use cookies:
http://jsfiddle.net/LLyB6/2/
JS variables never have been persistent, but there are two ways around this:
1.Cookies
2.Storage
Cookies are supported in all but the most ancient browsers, but they can be very unwieldly and difficult to use. On top of that, your browser sends cookies to the server with every pageload, so if it's only used by JavaScript then it's very inefficient.
Instead, you should probably look at the Storage option.
Saving an item is as simple as localStorage.itemname = value; Reading is as easy as localStorage.itemname, and deleting is as literal as delete localStorage.itemname
These values are saved across pageloads, but not sent to the server.
from:
Javascript global variable does not persist when navigate to another page (which also uses same js file)
What you are looking for is done using session / cookie / Appending query string:
Check this answer: PHP Pass variable to next page

HTTP cookie between two HTML pages

I have two HTML pages. After entering few inputs users will be redirected from first page to second page. Before redirecting the user to second HTML page(using window.location="new HTML URL"), I persist few of the user inputs in cookie using document.cookie DOM API.
When I am in the second HTML page, I could not retrieve the value from this cookie. I think since document object would have changed in the new HTML page, my cookie values become inaccessible.
Can someone tell me: how do I retrieve the value from a cookie persisted by one javascript in one HTML page in other HTML page i.e cookie written by HTML A's javascript in HTML B's javascript?
I don't have any server-side code, so I could not take advantage of server-side logic. Also I am not supposed to pass the values in URL. So I need a solution on plain javascript and HTML.
If some one has a better solution please let me know. Thanks
try to use localStorage instead of cookies,
// set your values in the first page
localStorage.setItem('itemKey', 'values');
// on the second page, retrieve them
var values = localStorage.getItem('itemKey');
you can use a jStorage plugin for cross browser behaviour.
also refer to this question for storing objects instead of strings
JAAulde is on point with his answer.
For what the OP is trying to do something like PHP would be great, in that case I wouldn't bother with cookies in order to just pass data between two pages, that's just silly. However, if true persistence was needed and the data requirements were simple cookies would be the way to go even while using a language such as PHP.
Those are rather draconian constraints, is this a class project? That said there aren't any other ways to do what you're attempting, save for an ugly and highly insecure hack of the DOM.

Using javascript to create a value in url and submit that value via form?

I have a site that request that they could send out different urls to clients to track what links are being used. I told them to use google analytics but they are requesting to stay away from it.
What they are asking is they want to send a url to there customers such as,
http://www.yoursite.com/?link=Nameoflink
They want to get that cookie and set it.
Then when the contact form is used they want to be able to submit that link name with the form submission to show what links are being used to go directly to there site.
I was told this is possible but i have no knowledge of that custom of javascript or cookie expertise... =/
You can get the value of the params passed in through the url with location.search. To get the value of the param, use the location.search and then find the specific url value, then set that in another hidden text field or something...
if (location.search){
var search = location.search.substr(1).split("&"),
url = search.split("=")[1];
document.getElementById('hiddenInput').value = url;
}
Note- the code above assumes that your search string only contains the URL value & that the URL is first. If not, it is likely this will fail. You can update the code to account for that by checking to make sure that search.split("=")[0]==="url" or expanding it to parse out all of the search params into an object that you can reference by key.
Yeah, google analytics would make this a lot easier, especially if you had a specific page that would serve as a drop-point, telling you how many people click this special link.
Without google analytics, you could get the GET variable values via a PHP or ASP page script and have them set that way, or you can use soley JavaScript to take care of cookie setting and retrieval.
For JavaScript, these links should point you in the right direction:
JavaScript cookies:
(I can only post one link, but check out W3C School's article on JavaScript cookie handling)
Extract GET values via JavaScript:
http://www.go4expert.com/forums/showthread.php?t=2163

Categories

Resources