Javascript: Create and Check for 2 Cookies [closed] - javascript

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
Ok, we run a website that has a shopping cart. Here's the scenario: a customer comes to the site and adds a product to their cart. They go to dinner and leave the item in their cart without checking out. The next day they want to buy the item. They go to the website and, without noticing it's in their cart already, attempt to add it to the cart again where they receive an error saying it's out of stock (because there is only one in stock and they have it in their cart already.) Now we lose a sale.
What I am trying to do is create 2 cookies: one that lasts 7 days (same as the cart cookie) and one for the session. The way it works is this: their first visit it creates 2 cookies: one for 7 days and one for the session. Now lets say the customer adds a product and closes their browser. The session cookie expires, leaving the 7 Day cookie there. Now when they come back, the script will check that the 7 Day Cookie is present, but not the session cookie, triggering some of my own code to be run.
The basic structure would be like this.
If 7DayCookie Exists {
If SessionCookie Exists {
End Script;
}
Else if SessionCookie Does Not Exist {
[Insert My Own Code]
}
}
Else if 7DayCookie Does not Exist {
Create SessionCookie;
Create 7DayCookie;
End Script;
}
Anybody able to make this for me? I assume it'll be a cinch for anybody that is very good with cookies and javascript.
Thanks in advance!
Final working code.
var wc = readCookie('wfwc');
var sc = readCookie('wfsc');
if (wc) {
if (sc) { }
else if (!sc) {
alert("It works.");
}
}
else if (!wc) {
createCookie('wfwc','week',7);
createCookie('wfsc','session',0);
}

I highly recommend the cookie functions from Peter Paul Koch's quirksmode. The 3 functions you need are createCookie, eraseCookie, and readCookie.
For the session cookie, you'll want to create a cookie that contains no "expires" header. for the 7 day cookie, you'll want to create a cookie that expires in 7 days.
Then, in javascript, you can do something like:
theme = readCookie("theme");
// if a cookie called "theme" isn't present, initialize.
if (!theme) {
theme = "sky.json";
}
I use PPK's scripts myself, I did change the == to === to avoid type coercion in the functions, although it's not strictly necessary.

Related

How set expiration date to an localStoarge item in Javascript? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed last year.
This post was edited and submitted for review last year and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
I am working on making premium access to my website. While doing so I want the login that had set the localStorage item as 1 to expire and get deleted after a month. I searched the web, but got confused as I am still learning JavaScript and jQuery. Can you help me out in setting expiration to the localStorage item? Here's the line of code that is setting the localStorage:
localStorage.setItem('ispremium', '1');
And my website is on Blogger platform, if that matters!
You can set the actual value as the first time user joined and the time to expire. And whenever the user opens again the website, you need to check that expiration date. But this is extremely unsecure, you shouldn't do that for sessions. Just to answer to your question, you can do the following:
const NAMESPACE = 'MY_ID';
const TIMESTAMP_MODEL = {
initial: null,
expiresOn: null
};
const TIMESTAMP = Date.now();
if (!JSON.parse(localStorage.getItem(NAMESPACE))) {
// when the user access your website for the first time, set the initial and expiresOn values:
localStorage.setItem(NAMESPACE, JSON.stringify({
initial: TIMESTAMP,
expiresOn: TIMESTAMP + 1000*60*60*24*30 // 1month in ms
}));
} else {
// then, when user access the website again, check the expiresOn, it it's value is bigger than current date
const EXPIRE_DATE = JSON.parse(localStorage.getItem(NAMESPACE)).expiresOn;
if (Date.now() > EXPIRE_DATE) {
console.log('session expired');
}
}
Normally this would be solved on the server side. The localStorage may be cleared if a user selects "clear browsing history" on some browsers. It may not be available across sessions if the user works with multiple browsers or incognito mode. Other than that someone with a bit of technical knowledge can insert the "ispremium" flag easily into his localStorage to gain access to your premium feature.
If you still want to solve this via client, you could store a timestamp instead of a boolean flag and check if the current time is still in the validity range. LocalStorage itself doesn't let you set an expiration date on entries.

how to get url parameters to appear on an html page WITHOUT php [duplicate]

This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 2 years ago.
I am developing a site in HTML (not PHP) and am trying to get url parameters to display on an appointment confirmation page. The appointment confirmation info is successfully passed to the URL parameters. But I can't figure out how to get them to appear on the page.
For example:
?name=John&date=Nov-26&Time=4pm
to appear on the html page as:
Name: John
Date: Nov 26
Time: 4pm
I have watched tutorials on youtube, followed instructions and copied code from examples on stackoverflow, but the results are a complete failure. Nothing appears on the pages at all.
If you reply, could you please provide the full code as I do do not know javascript and its exceedingly difficult for me to try to figure out where added options get inserted into any base coding you provide. For instance, if there is code with "var" in the option, does that replace the "var" that is in the base code offered, or does it get added to it? If it gets added to it, where does it go? Does it go after the semi-colon, or do I need to start a new curly bracket after the closed curly bracket?
Thanks in advance.
Try this - I am using URLSearchParams to extract the values from the URL and template literals to create the string
Change "?name=John&date=Nov-26&Time=4pm" to location.search on your site
<footer id="footer"></footer>
<script>
const srch = "?name=John&date=Nov-26&Time=4pm"; // location.search;
const parms = new URLSearchParams(srch);
document.getElementById("footer").innerHTML += `Name: <span id="name">${parms.get("name")}</span>
Date: <span id="date">${parms.get("date").replace(/-/g," ")}</span>
Time: <span id="time">${parms.get("Time")}</span>`;
</script>

how do I finish this program? (javascript) [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
The code below belongs to a crossrider extension I am currently attempting to develop that hopefully will sync bookmarks across browsers. This file is currently the background.js file it will first retrieve a snapshot of the bookmarks file from the local database then compare that to the current list of bookmarks and if there are any differences (either additions to the bookmarks list or subtractions) they will be be returned with the getChanges() function and then sent to the server, finally the script updates the snapshot and waits 30 seconds before restarting the process. I dont really know how to make the getChanges() function. It needs to return presumably a json object indicating both the additions and subtractions (both their titles and urls). If someone could write the code for the function that would be great. Thanks
appAPI.ready(function() {
// Poll every 30 seconds
setInterval(function() {
appAPI.db.async.get('prevBookmarks', function(value) {
// Load or initialize previous bookmarks list
var prevBookmarks = (value) ? value : {};
// Get current bookmarks
appAPI.bookmarks.getTree(function(nodes) {
// Save bookmark list for next comparison
appAPI.db.async.set('prevBookmarks', nodes);
// In your getChanges functions, traverse the bookmark trees collating
// changes and then post then to your API server using appAPI.request
var changes = getChanges(prevBookmarks, nodes);
appAPI.request.post({
url: http://yourAPIserver.com,
postData: changes,
contentType: 'application/json'
});
});
});
}, 30 * 1000);
});
Ok, you've got jQuery as one of your tags, so try this link: Compare 2 arrays which returns difference.
It returns the differences between two arrays. You'll have to perform this twice for what you're doing, once to figure out what is in current that is not in previous and vice versa. I don't know what properties are contained in your bookmarks so this simple example might not exactly suit your needs, but it might point you in the right direction.
Good luck and welcome to JavaScript!

Check if username already exists [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I want validate if username already exists while user insert the username in textbox or just after the textbox lost focus.
Jquery or Ajax?
Please, someone have examples of that?
In the onblur event of the text box, get the value of textbox and using jQuery ajax, make a call to a server page where you check it and return appropriate results. based on the results show the message to user (Available or Not Available)
Include jQuery in your page and have this script also
$(function(){
$("#txtUserName").blur(function() {
var userName=$(this).val();
if(userName!="")
{
$.get("checkusername.aspx?username="+userName+"&t="+$.now(),function(data){
if(data=="1")
{
$("#msgDiv").html("Not Available");
}
else
{
$("#msgDiv").html("Available :) ");
}
});
}
});
});
Assumuing checkusername.aspx page will read the querystring value and check in the database and return(Response.Write()) "1" or "0"
I prefer to use a Generic handler (.ASHX file) to do the server side checking instead of using the aspx file.
Both.
Use jQuery to react to the onblur event for the textbox. Then, use jQuery to make an ajax call to a controller to see if the user name is already taken.
$('#usernameTextBox').blur(function() {
alert('Make your ajax call here.');
});

Best way to provide a "tooltip tour" [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
What is the best way to provide a quick tour of a webapp using contextual tooltips?
Use case:
user navigates to the webapp
some form of popup asking if the user wants a guided tour of the interface
user can click next on each tooltip to be shown the next one
user can cancel the tour at any time by clicking some kind of exit X or button
Is there an easy library out there that does this?
Thanks!
The easiest way to do this is with Jeff Pickhardt's Guider-JS javascript tooltip walk-through library. It's very easy to use (although it has several very advanced features as well), and does exactly what you described.
You can check out this excellent example of a tooltip walk-through made with Guider-JS.
If you want to see a working example on a production site, it is used extensively on optimizely.com to provide help and walk-through guides for the user interface.
UPDATE: ZURB Foundation is now maintaining the excellent "Joyride" tooltip tour javascript library.
You could also write the tour part yourself using a linked list with an iterator that always calls a callback to set up the tooltip and one to close it. You can then use any tooltip script you want. Here's a quick proof of concept that should show you what I mean:
var toolTipList = {
tooltips: [],
currentTooltip: {},
addTooltip: function(tooltip){
var currentTail = this.tooltips.length > 0 ? this.tooltips[this.tooltips.length - 1] : {};
var newTail = {
tooltip: tooltip,
prev: currentTail
};
currentTail.next = newTail;
this.tooltips.push(newTail);
},
initialize: function(){
this.currentTooltip = this.tooltips[0];
this.currentTooltip.tooltip.callback();
},
next: function(){
if(this.currentTooltip.next){
this.currentTooltip.tooltip.close();
this.currentTooltip = this.currentTooltip.next;
this.currentTooltip.tooltip.callback();
}
}
};
for(var i = 0; i < 10; i++){
toolTipList.addTooltip({
callback: function(){
// called every time next is called
// open your tooltip here and
// attach the event that calls
// toolTipList.next when the next button is clicked
console.log('called');
},
close: function(){
// called when next is called again
// and this tooltip needs to be closed
console.log('close');
}
});
}
toolTipList.initialize();
setInterval(function(){toolTipList.next();}, 500);
​JSFiddle link

Categories

Resources