Javascript: - Refresh a page with a different time of refresh depending which page anchor they are viewing - refresh

I have this refresh script that refresh the page every 30 seconds.
<script>
var time = new Date().getTime();
$(document.body).bind("mousemove keypress", function(e) {
time = new Date().getTime();
});
function refresh() {
if(new Date().getTime() - time >= 30000)
window.location.reload(true);
else
setTimeout(refresh, 10000);
}
setTimeout(refresh, 10000);
</script>
Is it possible to set a different time of page refresh depending on the page anchor the user is viewing?
If user is viewing the default anchor page.php#main then the page will refresh every 30 seconds. But if the user is viewing anchor page #view1, then the page refresh is set to 60 seconds. Then on refresh returns the page to page.php#view1

SOLVED: I found an answer to my problem.
Using the window.name attribute I was able to set a value in seconds in the window.name and then a small javascript in each anchor area of the page which changed the window.name value when I needed a different time for refresh. I setup different values in the javascript function as follows.
function refresh() {
var secs;
if (window.name == '1'){
secs = '60000';
} else if (window.name == '2') {
secs = '120000';
} else if (window.name == '3'){
secs = '0';
} else {
secs = '180000'
}
if((new Date().getTime() - time >= secs)&&(secs != '0'))
window.location.reload(true);
Then in the html where the anchors are I added following scripts where I needed different times for refresh. I used a paragraph tag to help get it working.
<p id='demo'></p>
<script>
window.name = '1';
document.getElementById('demo').innerHTML = window.name;
</script>
<script>
window.name = '2';
document.getElementById('demo').innerHTML = window.name;
</script>

Related

Changing image based on location data output

I am trying to show/echo users location on a webpage using maxmind geoip2 paid plan, I also want to show different images based on the state/city names output.
For example, if my webpage shows the user is from New York, I would like to show a simple picture of New York, if the script detects the user is from Washington, the image should load for Washington.
This is the snippet I have tried but doesn't work.
<script type="text/javascript">
if
$('span#region=("New York")') {
// Display your image for New York
document.write("<img src='./images/NY.jpg'>");
}
else {
document.write("<img src='./images/different.jpg'>");
}
</script>
This is the code in the header.
<script src="https://js.maxmind.com/js/apis/geoip2/v2.1/geoip2.js" type="text/javascript"></script>
<script>
var onSuccess = function(geoipResponse) {
var cityElement = document.getElementById('city');
if (cityElement) {
cityElement.textContent = geoipResponse.city.names.en || 'Unknown city';
}
var countryElement = document.getElementById('country');
if (countryElement) {
countryElement.textContent = geoipResponse.country.names.en || 'Unknown country';
}
var regionElement = document.getElementById('region');
if (regionElement) {
regionElement.textContent = geoipResponse.most_specific_subdivision.names.en || 'Unknown region';
}
};
var onError = function(error) {
window.console.log("something went wrong: " + error.error)
};
var onLoad = function() {
geoip2.city(onSuccess, onError);
};
// Run the lookup when the document is loaded and parsed. You could
// also use something like $(document).ready(onLoad) if you use jQuery.
document.addEventListener('DOMContentLoaded', onLoad);
</script>
And this simple span shows the state name in body text of the Html when the page loads.
<span id="region"></span>
now the only issue is the image doesn't change based on users location, what am i doing wrong here?
Your example is missing some code, but it looks like you are running some code immediately and some code in a callback, a better way to do it is to have all the code in the callback:
// whitelist of valid image names
var validImages = ["NJ", "NY"];
// get the main image you want to replace
var mainImage = document.getElementById('mainImage');
if (mainImage) {
// ensure there is a subdivision detected, or load the default
if(geoipResponse.subdivisions[0].iso_code && validImages.includes( && geoipResponse.subdivisions[0].iso_code)){
mainImage.src = "./images/" + geoipResponse.subdivisions[0].iso_code + ".jpg";
} else {
mainImage.src = "./images/different.jpg";
}
}
Then just have the image you want to replace be:
<img src="data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs%3D" id="mainImage" />
Notes:
If you are using a responsive image, make sure your transparent gif is the same ratio height of to width as your final image to avoid page reflows.
You will have to load the different.jpg in the onError callback as well.

Check expiration times jQuery cookie

I have set a cookie using the jQuery cookie plugin. I've set the expiration on the cookie to one hour, so after that time the cookie is deleted. I want to display the remaining time left until the cookie expires to the user by retrieving this info from the cookie itself. is this possible using the jQuery cookies plugin? If not is there an eloquent way to achieve this?
I've set the expiration in this way:
jQuery.cookie('Cookie', timedCookie, { expires: new Date(+new Date() + (60 * 60 * 1000)) });
It's impossible to get a cookie's expiration using JavaScript. The only way to do this would be to store the expiration date somehow, such as in a javascript variable or in another cookie or local storage.
Here's an example:
var MINUTES = 1000 * 60;
var expireTime = new Date(+new Date + (60 * MINUTES)); // store the expiration time
jQuery.cookie('Cookie', timedCookie, { expires: expireTime });
var updateMessage = function(msg){
document.getElementById('time-left').innerHTML = msg;
};
var i = setInterval(function(){ // calculate time difference every ~1 min
var timeLeft = expireTime - new Date;
if(timeLeft <= 0){
updateMessage('Your session has expired.');
clearInterval(i);
} else {
updateMessage('You have ' + (timeLeft / MINUTES | 0) + ' minute(s) left in your cookied session.');
}
}, MINUTES);

Jquery Tool: Keep selected tab on refresh or save data

I am using jquery tool for tab Ui,
Now I want to keep tab selected on page reload. Is there any way to do that? below is my code
$(function() {
// setup ul.tabs to work as tabs for each div directly under div.panes
$("ul.tabs").tabs("div.panes > div");
});
Here is a simple implementation of storing the cookie and retrieving it:
function getCookie(c_name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == c_name) {
return unescape(y);
}
}
}
function setCookie(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
}
Then, to save/retrieve cookie data with jQuery UI Tabs:
$(function() {
// retrieve cookie value on page load
var $tabs = $('ul.tabs').tabs();
$tabs.tabs('select', getCookie("selectedtab"));
// set cookie on tab select
$("ul.tabs").bind('tabsselect', function (event, ui) {
setCookie("selectedtab", ui.index + 1, 365);
});
});
Of course, you'll probably want to test if the cookie is set and return 0 or something so that getCookie doesn't return undefined.
On a side note, your selector of ul.tabs may be improved by specifying the tabs by id instead. If you truly have a collection of tabs on the page, you will need a better way of storing the cookie by name - something more specific for which tab collection has been selected/saved.
UPDATE
Ok, I fixed the ui.index usage, it now saves with a +1 increment to the tab index.
Here is a working example of this in action: http://jsbin.com/esukop/7/edit#preview
UPDATE for use with jQuery Tools
According the jQuery Tools API, it should work like this:
$(function() {
//instantiate tabs object
$("ul.tabs").tabs("div.panes > div");
// get handle to the api (must have been constructed before this call)
var api = $("ul.tabs").data("tabs");
// set cookie when tabs are clicked
api.onClick(function(e, index) {
setCookie("selectedtab", index + 1, 365);
});
// retrieve cookie value on page load
var selectedTab = getCookie("selectedtab");
if (selectedTab != "undefined") {
api.click( parseInt(selectedTab) ); // must parse string to int for api to work
}
});
function getCookie(c_name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == c_name) {
return unescape(y);
}
}
}
function setCookie(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays === null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
}
Here is a working (unstyled) example: http://jsbin.com/ixamig/12/edit#preview
Here is what I see in Firefox when inspecting the cookie from the jsbin.com example:
This is what worked for me... at least I haven't run into any issues yet:
$('#tabs').tabs({
select: function (event, ui)
{
$.cookie('active_tab', ui.index, { path: '/' });
}
});
$('#tabs').tabs("option", "active", $.cookie('active_tab'));
I'm using: jQuery 1.8.2, jQuery UI 1.9.1, jQuery Cookie Plugin.
I set the "path" because in C# I set this value in a mvc controller which defaults to "/". If the path doesn't match, it wont overwrite the existing cookie. Here is my C# code to set the value of the same cookie used above:
Response.Cookies["active_tab"].Value = "myTabIndex";
Edit:
As of jQuery UI 1.10.2 (I just tried this version, not sure if it's broken in previous versions), my method doesnt work. This new code will set the cookie using jQuery UI 1.10.2
$('#tabs').tabs({
activate: function (event, ui) {
$.cookie('active_tab', ui.newTab.index(), { path: '/' });
}
});
The easiest way to survive between page refresh is to store the selected tab id in session or through any server-side script.
Only methods to store data on client side are: Cookies or localStorage.
Refer to thread: Store Javascript variable client side

Refresh a webpage just once after 5 seconds

I'm looking for a JavaScript solution (or whatever else) that will refresh a webpage ONLY once, after 5 seconds it has been opened. Is this possible without being stuck in a refresh loop?
try this:
setTimeout(function ()
{
if (self.name != '_refreshed_'){
self.name = '_refreshed_';
self.location.reload(true);
} else {
self.name = '';
}
}, 5000);
You could do this in many different ways, but I think the easiest would be to add a query string to the url after the refresh, allowing us to tell if the refresh has already occurred:
//Function to get query string value. Source: http://www.bloggingdeveloper.com/post/JavaScript-QueryString-ParseGet-QueryString-with-Client-Side-JavaScript.aspx
function getQuerystring(key, default_){
if (default_==null) default_="";
key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
var qs = regex.exec(window.location.href);
if(qs == null)
return default_;
else
return qs[1];
}
//check if our query string is already set:
if(getQuerystring(r) !== 1){
setTimeout(function(){window.location.href = window.location.href + '?r=1'},5000)
}
If there is the possibility that a query string is already present, you will have to account for that and change the '?' to an '&'.
Sure, if you don't mind using jquery you can do it via an ajax call after waiting 5 seconds. Just throwing you some sample code:
How to wait 5 seconds with jQuery?
$(document).ready(function() {
// Get data
$.ajax({
url : '/tommyStockExchange/Data',
dataType : 'html',
data : {
'format' : 'H',
'type' : 'E'
},
success : function(data) {
$("#executions").html(data);
},
statusCode : {
404 : function() {
alert('executions url 404 :(');
}
}
});
});
Make it redirect to the same page with a different #hash and in JS only register the redirect if the hash isn't set.
You just need to pass some sort of data between page loads. This can be done in a multitude of ways — use a cookie, a URL query parameter, or something on the server side. Query parameter example:
if (!location.search.match(/(\?|&|^)stopRefreshing(=|&|$)/))
{
setTimeout(function ()
{
var search = location.search;
location.search = search ? search + '&stopRefreshing' : 'stopRefreshing';
}, 5000);
}
Demo: http://jsbin.com/ofawuz/edit

Google Charts - "Missing Query for request id: 0"

This error only appears if I try to put two charts on the same page. Both charts work perfectly if they are the only one on the page. The minute I add the second only the first one loads and I get the "Missing Query for request id: 0" error.
Here is my js file for the chart:
function drawChart(title, queryPage, divToFill) {
var dataTab = null;
var query = new google.visualization.Query(queryPage);
var strSQL = "SELECT *";
query.setQuery(strSQL);
query.send(processInitalCall);
function processInitalCall(res) {
if(res.isError()) {
alert(res.getDetailedMessage());
} else {
dataTab = res.getDataTable();
// Draw chart with my DataTab
drawChart(dataTab);
}
}
function drawChart(dataTable) {
// Draw the chart
var options = {};
options['title'] = title;
options['backgroundColor'] = "#8D662F";
var colors = Array();
var x = 0;
if(currentCampaignId >= 0) {
while(x < dataTab.getNumberOfColumns() - 2) {
colors[x] = '#c3c1b1';
x++;
}
colors[x] = '#d2bc01';
}
else {
colors[0] = '#c3c1b1';
}
options['colors'] = colors;
options['hAxis'] = {title: "Week", titleColor: "white", textColor: "white"};
options['vAxis'] = {title: "Flow", titleColor: "white", textColor: "white", baselineColor: "#937d5f", gridColor: "#937d5f"};
options['titleColor'] = "white";
options['legend'] = "none";
options['lineWidth'] = 1;
options['pointSize'] = 3;
options['width'] = 600;
options['height'] = 300;
var line = new google.visualization.LineChart(document.getElementById(divToFill));
line.draw(dataTab, options);
}
}
Here is a snip from the index.php file:
<body>
<script type="text/javascript">
google.load('visualization', '1', {'packages': ['table', 'corechart']});
google.setOnLoadCallback(function(){
drawChart("Water", "waterData.php", "water");
drawChart("Air", "airData.php", "air");
});
</script>
<div id="water" style="text-align: center;"></div>
<div id="air" style="text-align: center;"></div>
</body>
It throws the error right at the query.send(processInitalCall); line, only on the second time it's called. Both the waterData.php and airData.php are identical except for the sig field. I did notice there was a field called reqId and it's set to 0.
Do I need to somehow change this reqId in these classes?
Probably too late, but for anyone interested...
When loading data from the data source, there will be a GET parameter in the request - tqx - with a value like: "reqId:0". You must return the same reqId in your response.
From the docs:
reqId - [Required in request; Data source must handle] A numeric
identifier for this request. This is used so that if a client sends
multiple requests before receiving a response, the data source can
identify the response with the proper request. Send this value back in
the response.
I don't have enough status in StackOverflow to write a comment, but this thread saved me an immense amount of time as well. THANK YOU
google visualization multiple charts with own data queries