Passing data between two aspx pages using javascript - javascript

I need help with passing around data between two aspx pages (these aspx pages are stored in SharePoint Designer). I have created some JavaScript that does some simple calculations for metrics on our site.
https://tandemhospitalpartners.sharepoint.com/SitePages/Home.aspx
The following JavaScript is in the aspx link listed above.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript">
window.onload = function ()
{
}
function p1()
{
totalPts = 137;
setTotalPts(totalPts);
divId = document.getElementById('avg'); // element represents the ID 'countdown' for the div
today = new Date(); //this represents todays date in the following format
//Weekday ex. "Tue"
//Month ex. "Aug"
//Todays Date ex. "08"
//Year ex. "2017"
//Time ex. "13:44:54 GMT - 0500 (Central Daylight Time"
svOpen = new Date(2017, 06, 17); // this represents the first day we accepted patients
one_day = 1000 * 60 * 60 * 24;
//milliseconds
//minutes
//seconds
//hours
//We have been open for 23 days
daysOpen = Math.ceil((today.getTime() - svOpen.getTime()) / (one_day));
//subtracting SVNH open date from current date
avgPts = parseFloat(totalPts)/parseFloat(daysOpen);
divId.innerHTML ="Average Patients Per Day: "+ avgPts.toFixed(1);
}
function GetDays(element)
{
var el = document.getElementById(element);
today = new Date();
var cmas = new Date(today.getFullYear(), 6, 12);
if (today.getMonth() == 6 && today.getDate() > 13) {
cmas.setFullYear(cmas.getFullYear() + 1);
}
var one_day = 1000 * 60 * 60 * 24;
el.innerHTML =" Days to open the second Hospital: "+Math.ceil((cmas.getTime() - today.getTime()) / (one_day));
}
function setTotalPts(totalPts)
{
totId = document.getElementById("leOne");
totId.innerHTML = "This is my total patients: " + totalPts.toString();
}
</script>
</head>
<body onload="p1(); GetDays('count'); setTotalPts();"+"text"> <!-- this onload is passing the div ID to the function p1( element )
element represents the ID -->
<div id='count' style="color: #e51400 ;
font-weight : 500;"></div>
</body>
<body>
<div id='avg' style="color: #e51400 ;
font-weight : 500;"></div>
</body>
<body>
<div id='leOne' style="color: #e51400 ;
font-weight : 500;"></div>
</body>
</html>
<!-- to keep a running count of the days i will have to subtract svOpen from todaysDate
My goal is to pass totalPts to an HTML ID that is on a different aspx file.
This is the link to the aspx file that contains the HTML ID I want to send it too.
https://tandemhospitalpartners.sharepoint.com/ININD/SitePages/Home.aspx
This is where I am really confused. I am not sure how to achieve this result. If anyone has ideas of how this could be done using JavaScript I would greatly appreciate it!

You cannot access another page's html from client side of another page as web is a stateless environment. But from the first page you can either pass the data through querystring to the next page or you can save data to localStorage, then navigate to the next page and retrieve data from localStorage. I prefer Querystring as it looks like its just a number you want to pass.
Suppose you have a button that opens up the second page
<asp:Button runat="server" ID="btnNext" OnClientClick="location.href='https://tandemhospitalpartners.sharepoint.com/ININD/SitePages/Home.aspx?totalPointes=' + getTotalPoints()" Text="Inind Home"></Button>
Then in the destination page the totalPoints from querystring and save it to the element. e.g.
$("#SomeID").val(getvaluefromQuerystring());

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script
src="https://code.jquery.com/jquery-3.2.1.js"
integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
crossorigin="anonymous"></script>
<script>
$(document).ready(function () {
$("#dvValue").html(getUrlParameter("totalPointes"));
});
//This function gets the querystring value from the querystring
function getUrlParameter(name) {
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
var results = regex.exec(location.search);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<div id="dvValue"></div>
</div>
</form>
</body>
</html>

Related

How to set a cache with Local Storage

I have a ads box and i want close it to by clicking x button so after it has been closed i don't want to se it until 24 hours with cache I created a localstorage but it's not working as i expected how should i edit my example
var showCase = Math.round(+new Date() / 1000);
document.getElementById("close_ads").addEventListener("click", function () {
if (typeof localStorage.showCase == 'undefined' || parseInt(localStorage.showCase) <= (showCase - 3600)) {
localStorage.showCase = showCase;
document.getElementById('reklam_box').style.display = 'none';
}
});
<div id="ads_box">
Hi..I am a ads..
<span id="close_ads">Close ads and don't show unit for 24 hours</span>
</div>
You need to use Localstorages .setItem() and .getItem check this out.
https://www.taniarascia.com/how-to-use-local-storage-with-javascript/
So something like this
// set the item
localStorage.setItem('showCase', 3600);
//get the item
var showCase = localStorage.getItem('showCase');
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example</title>
</head>
<body>
<div id="ads_box">
Hi..I am a ads..
<span id="close_ads">Close ads and don't show unit for 24 hours</span>
</div>
<script>
var dontShowUntil = new Date(new Date().getTime() + 60 * 60 * 24 * 1000);
document.getElementById("close_ads").addEventListener("click", function () {
localStorage.dontShowUntil = dontShowUntil;
document.getElementById('ads_box').style.display = 'none';
});
if (new Date(localStorage.dontShowUntil) > new Date()) {
document.getElementById('ads_box').style.display = 'none';
}
</script>
</body>
</html>
useful linkes:
https://johnresig.com/blog/dom-storage/
https://developer.mozilla.org/en-US/docs/Web/API/Storage
NOTICE : when working with localStorage with array of objects you must save it like that:
Just convert the objects to JSON strings:
localStorage.setItem("savedData", JSON.stringify(objects));
var objects = JSON.parse(localStorage.getItem("savedData")));

How to use an element property to pass a variable from Javascript

I'm attempting to send emails using an HTML template.
I've looked at this post:
(https://stackoverflow.com/questions/33178702/passing-variables-into-html-code)
Would either of the two code examples be close to something that could work to pass the variables from the Javascript to the HTML template?
My javascript variables are named detail2, detail3, detail4, detail5 and detail6.
1st attempt:
<html>
<head>
<script>
{
var detail2 = document.getElementById("detail2").innerHTML;
var detail3 = document.getElementById("detail3").innerHTML;
var detail4 = document.getElementById("detail4").innerHTML;
var detail5 = document.getElementById("detail5").innerHTML;
var detail6 = document.getElementById("detail6").innerHTML;
}
}
</script>
</head>
<body>
<p>
<br>"Punctual? " document.getElementById('detail2').value<br>
<br>"Attention to detail? " document.getElementById('detail3').value<br>
<br>"Overall Professionalism? " document.getElementById('detail4').value<br>
<br>"Date of Service: " document.getElementById('detail5').value<br>
<br>"Notes/Details: " document.getElementById('detail6').value<br>
</p>
</body>
</html>
2nd attempt:
<html>
<head>
<script>
{
<input type="hidden" id="Detail2" value="detail2" />
<input type="hidden" id="Detail3" value="detail3" />
<input type="hidden" id="Detail4" value="detail4" />
<input type="hidden" id="Detail5" value="detail5" />
<input type="hidden" id="Detail6" value="detail6" />
}
}
</script>
</head>
<body>
<p>
<br>"Punctual? " document.getElementById('detail2').value<br>
<br>"Attention to detail? " document.getElementById('detail3').value<br>
<br>"Overall Professionalism? " document.getElementById('detail4').value<br>
<br>"Date of Service: " document.getElementById('detail5').value<br>
<br>"Notes/Details: " document.getElementById('detail6').value<br>
</p>
</body>
</html>
Finally, the method given on GAS Dev is below, but this only confuses me more. I am sure I've been at this too long and I'm burned out, I just can't seem to see the answer on this one.
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<table>
<? for (var i = 0; i < data.length; i++) { ?>
<tr>
<? for (var j = 0; j < data[i].length; j++) { ?>
<td><?= data[i][j] ?></td>
<? } ?>
</tr>
<? } ?>
</table>
</body>
</html>
If anyone can help it's much appreciated!
Below is the Javascript from the .gs script file.
function SendEmail() {
// initialize data
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var range = sheet.getDataRange();
var values = range.getValues();
// iteration loop
for (var i = 1; i<values.length; i++) {
// current times for comparator
var month = new Date().getMonth(); // returns today as 0-11 -- Jan is 0
var day = new Date().getDate(); // returns today as 1-31
var hour = new Date().getHours(); // returns today as 0-23
var minute = new Date().getMinutes(); // returns today as 0-59
// pull data from spreadsheet rows
var company = values[i][0];
var rating = values[i][1];
var detail1 = values[i][2];
var detail2 = values[i][3];
var detail3 = values[i][4];
var detail4 = values[i][5];
var detail5 = values[i][6];
var sendTime = values[i][7];
// character send times for comparator
var cSendMonth = sendTime.getMonth(); // returns sendMonth as 0-11 -- Jan is 0
var cSendDay = sendTime.getDate(); // returns sendDay as 1-31
var cSendHour = sendTime.getHours(); // returns sendHour as 0-23
var cSendMinute = sendTime.getMinutes(); // returns sendMinute as 0-59
// comparator
if(cSendMonth == month) {
if(cSendDay == day) {
if(cSendHour == hour) {
if(cSendMinute == minute) {
var htmlBody = HtmlService.createHtmlOutputFromFile('mail_template').getContent();
MailApp.sendEmail({
to: Session.getActiveUser().getEmail(),
subject: 'Test Email markup2 - ' + new Date(),
htmlBody: htmlBody,
});
} // end if minute test
}// end if hour test
}// end if day test
}// end if month test
}// end for loop
}
Can you try:
<html>
<head>
<script>
(function() {
var detail2 = document.getElementById("detail2").innerHTML;
document.getElementById("detail2_val").innerHTML = detail2;
})();
</script>
</head>
<body>
<p>
<br>"Punctual?" <span id="detail2_val"></span><br>
</p>
</body>
</html>
Currently, this line:
var htmlBody = HtmlService.createHtmlOutputFromFile('mail_template').getContent();
will not evaluate a template.
The method being used is:
createHtmlOutputFromFile('mail_template')
HtmlService has quite a few methods for creating html content. You need to use:
HtmlService.createTemplateFromFile(filename).evaluate()
There are some possible things that could go wrong in your overall work flow. If the situation is one in which you are writing data, and then immediately trying to read that same data that was just written, there could be a problem with the new data not being available to be read in such a short time span.
I would use:
SpreadsheetApp.flush();
immediately after writing the new data, and before creating the template.
Only your third html example has code for a template. To retrieve data and put it into a template, a scriptlet must either run a function, that then retrieves the data, or the data must be in global variables. The situation with global variable makes no sense, because you are using dynamic data, so a function would need to run to first put the data into a global variable. The function might as well just return the data directly. So, your scriptlet will probably need to run a server side function and return text or HTML to the html template. You probably need to use a printing scriptlet.
Apps Script documentation - force printing scriptlets

Javascript .getHours() not working properly

Why am I not getting a zero, but an "18", from .getHours(), when comparing two dates that are separated by only seconds?
Here is the code:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<span id="test">starting...</span>
<script>
var a = document.getElementById("test");
window.setInterval(myHourCheck, 1000);
var originalDate = new Date();
function myHourCheck() {
var current = new Date();
var original = originalDate;
var timeDelta = current.getTime() - original.getTime();
var hours = new Date(timeDelta).getHours();
a.innerHTML = hours;
}
</script>
</body>
</html>
Stepping through confirms that only seconds separate current from original.
new Date constructs a Date object with your local time zone. The hour offset is screwing you up.
You can get around this by using the UTC versions of the methods:
new Date(0).getUTCHours() === 0

javascript read number of hours worked

Write the JavaScript to read the number of hours worked from the user. Then write the JavaScript to calculate how much money the user made if they were paid $12/hour for the first 40 hours worked, and $18/hr for all hours worked over 40. Then use the alert() function to print the total amount to the user.
what code do I have to use
var y = prompt("Enter a Value","");
Lol #OverComplicated. The answer is there just remake a better version and try your homework before being spoonfed.
var BarryScott = {
PricePerHour: 12,
HoursWorkedByBarry: 0,
PrintPayment: function() {
if ( this.HoursWorkedByBarry > 40) {
var RemainHours = this.HoursWorkedByBarry - 40;
alert(this.PricePerHour * 40 + RemainHours * 18);
} else {
alert(this.PricePerHour * this.HoursWorkedByBarry);
}
},
AskHoursFromBarry: function() {
this.HoursWorkedByBarry = prompt("Enter Hours you worked");
this.PrintPayment();
}
}
BarryScott.AskHoursFromBarry();
Create a folder and place your index.html and javascript code inside.
Run index.html .
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Im lazy to do my assignment</title>
<script src = "billhours.js"></script>
</head>
<body>
</body>
</html>
billhours.js
var getInput = prompt("Enter Number of Hours worked");
var first40hrs = billHours(40, 12);
var over40hrs = billHours(getInput - 40, 18);
var totalSalary = first40hrs + over40hrs;
alert("Total Salary is "+totalSalary);
function billHours(hours, rate){
return hours*rate;
}
//This function only works for hours 40 and above.
//It's your job to put conditional statements if hours is below 40. Keep Coding.

Can't get JavaScript output on website

The website is supposed to display a message counting down to the tax day. I can't seem to get anything to display on the page. The scrollbar doesn't even show up with the color even though I put in the write code. Some advice please.
<!DOCTYPE HTML>
<html>
<head><meta charset="utf-8">
<title>TaxDay</title>
<script type="text/javascript">
<!-- Hide from old browsers
function scrollColor() {
styleObject=document.getElementsByTagName('html')[0].style
styleObject.scrollbarFaceColor="#857040"
styleObject.scrollbarTrackColor="#f4efe9"
}
function countDown() {
var today = new Date()
var day of week = today.toLocaleString()
dayLocate = dayofweek.indexOf(" ")
weekDay = dayofweek.substring(0, dayLocate)
newDay = dayofweek.substring(dayLocate)
dateLocate = newday.indexOf(",")
monthDate = newDay.substring(0, dateLocate+1)}
yearLocate = dayofweek.indexOf("2016")
year = dayofweek.substr(yearLocate, 4)
var taxDate = new Date ("April 16, 2017")
var daysToGo = taxDate.getTime()-today.getTime()
var daysToTaxDate = Math.ceil(daysToGo/(1000*60*60*24))
function taxmessage() {
var lastModDate = document.lastModified
var lastModDate = lastModDate.substring(0,10)
taxDay.innerHTML = "<p style='font-size:12pt; font-
family:helvetica;'>Today is "+weekDay+" "+monthDate+" "+year+".
You have "+daysToTaxDate+" days to file your taxes.</p>"
}
}
//-->
</script>
The <div> id is taxDay if it's relevant. The body onLoad event handlers are scrollColor(); countDown(); and taxmessage().
you are not closing the countdown() function before the taxmessage() function - meaning that taxmessage is nested within countdown(). Also you do not have semicolons ";" after each line of the js. You should rewrite the code to either include the function of taxmessage() or close out countdown() first and call taxmessage with arguments passed to get the date variables.
check your console for errors

Categories

Resources