How to handle cookies in JavaScript? [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the “best” way to get and set a single cookie value using JavaScript
I am working on a project where it requires to check cookie and tell whether it is 20 minutes old or not. So I have written once code which is like this.
This is only javascript code I have pasted.
function checkcookie()
{
var difftime= getcookie();
// further operation comes here
}
var cookieminutes;
function getcookie()
{
var start = document.cookie.indexOf("expires");
var cookiedate;
if(start==-1)
{
cookiedate = new Date();
document.write("Start equal to -1");
document.cookie="expires="+cookiedate+",path=0,domain=0";
cookieminutes= cookiedate.getMinutes();
}
else
{
document.write("Start not equal to -1");
var date = new Date();
var minutes = date.getMinutes();
document.write("The difference is "+minutes);
document.write("<br />Cookie minutes is "+cookieminutes);
return (minutes-cookieminutes);
}
}
In function getcookie the variable cookieminutes is coming as undefined. But as I know since it is a global variable it should have the value.
Can anybody please tell what is the solution for this.?

You're only setting a value for cookieminutes in the top section of the if statement, so any references in the else section will be null.
Try this:
function getcookie()
{
var start = document.cookie.indexOf("expires");
var cookiedate;
cookiedate = new Date();
cookieminutes = cookiedate.getMinutes();
if(start==-1)
{
document.write("Start equal to -1");
document.cookie="expires="+cookiedate+",path=0,domain=0";
}
else
{
document.write("Start not equal to -1");
var date = new Date();
var minutes = date.getMinutes();
document.write("The difference is "+minutes);
document.write("<br />Cookie minutes is "+cookieminutes);
return (minutes-cookieminutes);
}
}

If you want to use global variables (generally bad design) set and access them explicitly with window. E.g.:
window.cookieminutes = cookiedate.getMinutes();
and later:
document.write("Cookie minutes is "+window.cookieminutes);
And drop the var cookieminutes;
As I said in my comment, it looks like if getcookie is being called for the first time on a given page load, and the cookie exists (start != -1), cookieminutes is never set. You need to make sure you don't use undefined variables.

Related

How to add js condition to know if this is the first traffic in last n minutes

Please i am trying to make a JS code to redirect user if this is the first traffic in last n minutes and if not just click a button in the page and i have written a script to do that but i just donnot know what is the condition which state if this is the first traffic so anyone can help ? and if this is not possible anyone has an idea how to do that using JS
if (condition) {
window.location.href = "http://www.exapmle.com";
} else {
document.getElementById('button-login').click();
}
You could approach this with cookies and set an expiration date, but it might behave oddly, since some browsers/browser versions handle cookies differently.
If you are using vanilla Javascript, defer your script tag (read about the defer property if it's new to you), like this:
<script defer src="./myScriptFile.js"></script>
Check for the cookie, do what you have to do and then set it again. Your script file should look like this:
function getCookie(name) {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length === 2) return parts.pop().split(";").shift();
}
function setLastAccess() {
const date = new Date();
const expireMs = 5 * 60 * 1000; // 5 minutes
date.setTime(date.getTime() + expireMs);
document.cookie = `lastAccess=${new Date().getTime()};expires=${date.toUTCString()};path=/`;
}
if(!getCookie('lastAccess')) {
// do what have you have to do when last access was before 5 minutes ago or it's the first access
setLastAccess(); // set your last access at the end
} else {
// this will run when last access was not before 5 minutes ago
}

Display a JavaScript variable in a page loaded in innerHTML [duplicate]

This question already has answers here:
Load scripts inside innerHTML [duplicate]
(2 answers)
Closed 4 years ago.
I have an HTML page that loads within another HTML page via innerHTML. After several days of work, this script works fine and another JS file is called for the interior page, a file (named "Unified_app.js") that basically runs some date calculations. Everything is working fine and the correct dates print to the console. However, I can't figure out on the page within a page can display the console dates. Document.write does not work in this situation (I'm assuming because of the tags are not read properly?), so I need to come up with a workaround. Any ideas?
This is the innerHTML functions as I have them:
function getYearOffset(strCutoffDate, intYearOffset)
{
var datCurrentDate = new Date();
var intCurrentYear = datCurrentDate.getFullYear();
var intCurrentMonth = strCutoffDate.substr(5, 2) - 1;
var intCurrentDay = strCutoffDate.substr(8, 2);
var datCutoffDate = new Date(intCurrentYear, intCurrentMonth, intCurrentDay);
if (Number(datCurrentDate) < Number(datCutoffDate))
{
var datRequestedDate = new Date(datCurrentDate.getFullYear(), intCurrentMonth, intCurrentDay);
}
else
{
var datRequestedDate = new Date(datCurrentDate.getFullYear() + intYearOffset, intCurrentMonth, intCurrentDay);
}
return datRequestedDate.getFullYear();
}
var script = document.createElement("script");
script.src = "/resource/resmgr/scripts/Unified_app.js";
document.head.appendChild(script);
function getInclude(strIncludeContainer, strIncludeURL)
{
var strPage = '';
var intIndexOfBodyOpen = 0;
var intIndexOfBodyClose = 0;
var objXhttp;
objXhttp = new XMLHttpRequest();
objXhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
strPage = this.responseText;
intIndexOfBodyOpen = strPage.indexOf('<body>');
intIndexOfBodyClose = strPage.indexOf('</body>');
document.getElementById(strIncludeContainer).innerHTML = strPage.substring(intIndexOfBodyOpen + 6, intIndexOfBodyClose);
}
};
objXhttp.open("GET", strIncludeURL, true);
objXhttp.send();
}
I'm using:
<script>document.write(award_year1);</script>
to write the following date calls:
const date = new Date();
let offset = 0;
const threshold = new Date();
threshold.setMonth(3); //January is 0!
threshold.setDate(3);
if (Date.now() > threshold) {
offset = 1;
}
var theDate = new Date();
var award_year1 = date.getFullYear() + offset;
var award_year2 = date.getFullYear() + 1 + offset;
console.log(award_year1);
console.log(award_year2);
When loading the page-within-a-page HTML file or the interior page itself I get the correct date calculations sent to the console, but I can't seem to get them to print within the innerHTML page when loaded into the other page. Any ideas you could send me down the right path? This is probably beyond my level of understanding of JavaScript. I thought perhaps my code was not in the correct order but I've been fiddling with this and can't seem to figure out where or why.
I'm not sure if this will solve the problem but you can try it.
As you said the document.write will not be triggered cause your JS is loaded before your DOM is.
document.addEventListener("DOMContentLoaded", function(event) {
//your functions
});
Maybe this will help you out
I guess this is just not possible. I ended up replacing the innerHTML with an iframe and that seems to have worked so that I can now use script tags. Not an ideal solution but it works

using the HolidayAPI for bank holidays

the Question:
How can I use the API to return a boolean value if the date is a bank holiday?
I have done some research and found a great, and free API which contains bank holidays, however I am having trouble using it: http://holidayapi.com/
if i was to use this code:
var year = 2016;
var month = 3;
var day = 25;
var isAHoliday = false;
$.getJSON(
"http://holidayapi.com/v1/holidays?country=GB&year=" + year + "&month=" + month + "&day=" + day, function (data) {
console.log(data); //DOES NOT DISPLAY IN CONSOLE
if (data.holidays.length > 0) {
// BANK HOLIDAY
isAHoliday = true;
}
else {
//IS NOT BANK HOLIDAY
//AND NOTHING NEEDS TO BE DONE
}
});
i want to be able to return a true or false value depending on if this returns any data or not, however im doing something wrong as the getJSON request is not being called, please could someone correct me where i have gone wrong?
http://holidayapi.com/v1/holidays?country=GB&year=2016&month=03&day=25 returns {"status":200,"holidays":[{"name":"Good Friday","country":"GB","date":"2016-03-25"}]}
http://holidayapi.com/v1/holidays?country=GB&year=2016&month=03&day=26 returns {"status":200,"holidays":[]}
it appears this is causing an issue: "http://holidayapi.com/v1/holidays?country=GB&year=" + year + "&month=" + month + "&day=" + day; if i pass one of the 2 URL's in above i get the correct result, I am having a play now with this
https://jsfiddle.net/dcxk6ens/
If you simply want to return a true value if the selected date is a holiday, or false if it is not, you could use a function like this:
(Please note that jsfiddle will not execute any AJAX calls to URLs using the "http://" protocol, since it is not secure.)
function isDateAHoliday(y, m, d) {
var jsonURL = "http://holidayapi.com/v1/holidays?country=GB&year=" + y + "&month=" + m + "&day=" + d;
var isAHoliday = false;
$.getJSON(jsonURL, function (data) {
// If the date is a holiday
if (data.holidays.length > 0) {
// Do some things
isAHoliday = true;
}
// Check values
console.log("JSON DATA: ", data);
console.log("Holiday?: " + isAHoliday);
return isAHoliday;
});
}
isDateAHoliday("2016", "3", "25");
If you wanted to return the name and country of the holiday as well, you could substitute isAHoliday = data.holidays[0]; inside of the if statement.
The holidays object must be called as a child of the returned data object:
Since the holidays object is an array you'll also need to use an index to access an item. Assuming there is at least one item returned, you would get the date like so:
var myDate = data.holidays[0].date;
However you should always check that there's at least one object in the array before getting the first one:
if(data.holidays.length > 0){...}
Incidentally, if all you want to do is check if there's a holiday on any particular day then this if statement is all you'll need, since an array length of more than zero means there's at least one holiday.
Edit
A full answer to your question, you could put this inside the .done() method:
var isAHoliday = false;
if(data.holidays.length > 0){
// There's at least one holiday today!
isAHoliday = true;
}
You don't have to declare a local variable, you'll probably use one that's declared elsewhere but that's up to you.

Having issue with getting an .innerHTML to work properly while inside of an if statement

I have an .innerHTML statement that isn't working correctly, but only while within an if statement.
document.getElementById("music").innerHTML = "[MUSICPLAYERCODE]";
is the code that I'm using, and it's within this.
<script type="text/javascript">
var thedate - new Date();
var hourofday = thedate.getHours();
if(hourofday == 0) {
document.getElementById("music").innerHTML = "[MUSICPLAYERCODE]";
}
</script>
While outside of the if statement, the code works completely fine, however, inside the if statement it refuses to work. Even if I change the condition to just a plain true, the code still will not execute. I'm new to javascript, and I can't seem to find any error after looking for a couple hours. If it helps at all, the music player I'm using is at Billy Tumblr Audio Player.
I think you have added not just the if condition but also the code related to date calculation.
There you have a syntax error, used - instead of =. In your browser console you should see an error like Uncaught SyntaxError: Unexpected token -
var thedate = new Date();
// ^ = not -
var hourofday = thedate.getHours();
if (hourofday == 0) {
document.getElementById("music").innerHTML = "[MUSICPLAYERCODE]";
}
var thedate - new Date(); ?
Change it to:
var thedate = new Date();
You can try like this.
window.onload=function(){
var thedate = new Date();
var hourofday = thedate.getHours();
if(hourofday == 0) {
document.getElementById("music").innerHTML = "<H1>[MUSICPLAYERCODE]</H1>";
}
};

Windows Gadget reading specific information from Excel with Javascript

Hi I am trying to write a Windows Gadget that reads out information from an Excelsheet.
The Excelsheet entails a the dates, formated, of the whole year in column A2:A366 and the following columns are the names of the employes B1:Q1.
The gadget is to display the current day and who is marked absent. For each day a person is absent the cell is marked with an X.
I am not a Javascript programmer. And need help. I think I have the basic setup already, and I hope you can help me find my missings.
Explanation:
With the getToday function I am trying to get the date from the PC and format it to a string which I want to use to find in the Column A, which is set to be an array. The same function ist ment to give me back the right row in which it should look for the Xs. If it finds an X it is supposed to return the name of the column i.e the name of the employee.
function getToday (){
var today;
var currentDate = new Date()
var day = currentDate.getDate()
var month = currentDate.getMonth() + 1
var year = currentDate.getFullYear()
today = d.toString (day + "." + month + "." + year);
}
function refreshData(){
oExcel = new ActiveXObject('Excel.Application');
oWkBooks = oExcel.Workbooks.Open("C:\\Program Files\\Windows Sidebar\\Gadgets\\ExcelGadget.Gadget\\test.xlsx");
oExcelSheet = oWkBooks.Worksheets();
oExcelSheet.Activate();
oExcel.ActiveWorkbook.RefreshAll();
oExcel.ActiveWorkbook.SaveAs("C:\\Program Files\\Windows Sidebar\\Gadgets\\ExcelGadget.Gadget\\test.xlsx");
oWkBooks.Close();
location.reload();
}
function fetchData() {
function fetchData() {
$('#msg').html("Loading...");
$('#msg').show();
var oExcel;
var oExcelSheet;
var oWkBooks;
var cols;
oExcel = new ActiveXObject('Excel.Application');
oWkBooks = oExcel.Workbooks.Open("C:\\Program Files\\Windows Sidebar\\Gadgets\\ExcelGadget.Gadget\\test.xlsx");
}
function findToday(stringArray){
for (var j=0; j<stringArray.length; j++) {
if (stringArray[j].match (var today) return cell;
return -1;
}
function returnAbwesentheit() {
var name = name.arr;
for (i=2;i<x.length;i==23) {
if ("cell"=="x") {
document.write (Name(cell));
else
return null;
}
}
::UPDATE::
I had a flash of inspiration. I think I am making this to difficult for myself. Maybe I could make excel do the finding of the date and who is absent. Then I would only generate the Outcome with Javascript into the Windows Gadget.

Categories