Auto refreshing page with saved input - javascript

I'm trying to make a JSP that refresh itself every 2scd approximately and keep what the user tip in input form.
My idea was to save the input with javascript, add them to the URL and refresh the page, then retrieve and set the input.
This is my JS code :
$(document).ready(function () {
function refreshPage(){
var mapValue = new Array();
var mapName = new Array();
var i = 0;
$(".positionInput").each(function() {
mapValue[i] = $(this).val();
mapName[i] = $(this).attr("name");
i++;
});
var parameters = "";
for(i = 0; i < mapName.length; i++){
if(mapValue[i] != ""){
parameters += "?" + mapName[i] + "=" + mapValue[i];
}
}
window.location.href = "http://localhost:8080/drawinguess/waitingplayer.jsp" + parameters;
setTimeout(refreshPage, 2000); //execute itself every 2s
}
refreshPage();
});
But the timer get crazy (even with 1mn delay), it refresh itself as fast as he can with window.location.href (without this, it's working fine)
Thanks in advance if you have any other idea or if I'm making something wrong

You could try and use local storage for this. The best way would be that instead of refreshing the entire page, you only refresh what is needed by having services set up and using an async function like fetch() to hit those services and update the page.

Related

Reload Parent Window without POST

I am trying to reload a parent window (same domain) with javascript from within an iframe.
window.parent.location.href = window.parent.location.href;
does not work here for some reason (no javascript errors).
I don't believe it is a problem with same origin policy, as the following works:
window.parent.location.reload();
The problem with this option is if the last request was a POST, it gets reloaded as POST.
Any ideas why the first option wouldn't work? Otherwise, is there another method that will reload the page without resubmitting any form data (e.g. perform a fresh GET request to the parent page URL)?
I have also tried:
top.frames.location.href = top.frames.location.href;
window.opener.location.href = window.opener.location.href
and various other iterations.
I tried this code:
window.location.href = window.location.href;
in an ordinary page (no frames) and it had no effect either. The browser must detect that it is the same URL being displayed and conclude that no action needs to be taken.
What you can do is add a dummy GET parameter and change it to force the browser to reload. The first load might look like this (with POST data included, not shown here of course):
http://www.example.com/page.html?a=1&b=2&dummy=32843493294348
Then to reload:
var dummy = Math.floor(Math.random() * 100000000000000);
window.parent.location.href = window.parent.location.href.replace(/dummy=[0-9]+/, "dummy=" + dummy);
Phari's answer worked for me, with a few adjustments to fit my use case:
var rdm = Math.floor(Math.random() * 100000000000000);
var url = window.parent.location.href;
if (url.indexOf("rdm") > 0) {
window.parent.location.href = url.replace(/rdm=[0-9]+/, "rdm=" + rdm);
} else {
var hsh = "";
if (url.indexOf("#") > 0) {
hash = "#" + url.split('#')[1];
url = url.split('#')[0];
}
if (url.indexOf("?") > 0) {
url = url + "&rdm=" + rdm + hsh;
} else {
url = url + "?rdm=" + rdm + hsh;
}
window.parent.location.href = url;
}
I'm sure this could be more efficient, but works ok.

How to display a loading animation while file is generated for download?

I have a web application where the user can generate PDF and PowerPoint files. These files may take some time to generate, so I would like to be able to display a loading animation while it generates. The problem here is that I have no mean to know when the download has started. The animation never goes away.
I am aware that it could be possible to generate the file "on the side" and alert the user when the file is ready for download using AJAX, but I prefer "locking" the user while he waits for the download to start.
To understand what needs to be done here, let's see what normally happens on this kind of request.
User clicks the button to request the file.
The file takes time to generate (the user gets no feedback).
The file is finished and starts to be sent to user.
What we would like to add is a feedback for the user to know what we are doing... Between step 1 and 2 we need to react to the click, and we need to find a way to detect when step 3 occurred to remove the visual feedback. We will not keep the user informed of the download status, their browser will do it as with any other download, we just want to tell the user that we are working on their request.
For the file-generation script to communicate with our requester page's script we will be using cookies, this will assure that we are not browser dependent on events, iframes or the like. After testing multiple solutions this seemed to be the most stable from IE7 to latest mobiles.
Step 1.5: Display graphical feedback.
We will use javascript to display a notification on-screen. I've opted for a simple transparent black overlay on the whole page to prevent the user to interact with other elements of the page as following a link might make him lose the possibility to receive the file.
$('#downloadLink').click(function() {
$('#fader').css('display', 'block');
});
#fader {
opacity: 0.5;
background: black;
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="fader"></div>
Click me to receive file!
</body>
Step 3.5: Removing the graphical display.
The easy part is done, now we need to notify JavaScript that the file is being downloaded. When a file is sent to the browser, it is sent with the usual HTTP headers, this allows us to update the client cookies. We will leverage this feature to provide the proper visual feedback. Let's modify the code above, we will need to set the cookie's starting value, and listen to its modifications.
var setCookie = function(name, value, expiracy) {
var exdate = new Date();
exdate.setTime(exdate.getTime() + expiracy * 1000);
var c_value = escape(value) + ((expiracy == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = name + "=" + c_value + '; path=/';
};
var getCookie = function(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 == name) {
return y ? decodeURI(unescape(y.replace(/\+/g, ' '))) : y; //;//unescape(decodeURI(y));
}
}
};
$('#downloadLink').click(function() {
$('#fader').css('display', 'block');
setCookie('downloadStarted', 0, 100); //Expiration could be anything... As long as we reset the value
setTimeout(checkDownloadCookie, 1000); //Initiate the loop to check the cookie.
});
var downloadTimeout;
var checkDownloadCookie = function() {
if (getCookie("downloadStarted") == 1) {
setCookie("downloadStarted", "false", 100); //Expiration could be anything... As long as we reset the value
$('#fader').css('display', 'none');
} else {
downloadTimeout = setTimeout(checkDownloadCookie, 1000); //Re-run this function in 1 second.
}
};
#fader {
opacity: 0.5;
background: black;
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="fader"></div>
Click me to receive file!
</body>
Ok, what have we added here. I've put the set/getCookie functions I use, I don't know if they are the best, but they work very well. We set the cookie value to 0 when we initiate the download, this will make sure that any other past executions will not interfere. We also initiate a "timeout loop" to check the value of the cookie every second. This is the most arguable part of the code, using a timeout to loop function calls waiting for the cookie change to happen may not be the best, but it has been the easiest way to implement this on all browsers. So, every second we check the cookie value and, if the value is set to 1 we hide the faded visual effect.
Changing the cookie server side
In PHP, one would do like so:
setCookie("downloadStarted", 1, time() + 20, '/', "", false, false);
In ASP.Net
Response.Cookies.Add(new HttpCookie("downloadStarted", "1") { Expires = DateTime.Now.AddSeconds(20) });
Name of the cookie is downloadStarted, its value is 1, it expires in NOW + 20seconds (we check every second so 20 is more than enough for that, change this value if you change the timeout value in the javascript), its path is on the whole domain (change this to your liking), its not secured as it contains no sensitive data and it is NOT HTTP only so our JavaScript can see it.
VoilĂ ! That sums it up. Please note that the code provided works perfectly on a production application I am working with but might not suit your exact needs, correct it to your taste.
This is a simplified version of Salketer's excellent answer. It simply checks for the existence of a cookie, without regard for its value.
Upon form submit it will poll for the cookie's presence every second. If the cookie exists, the download is still being processed. If it doesn't, the download is complete. There is a 2 minute timeout.
The HTML/JS page:
var downloadTimer; // reference to timer object
function startDownloadChecker(buttonId, imageId, timeout) {
var cookieName = "DownloadCompleteChecker";
var downloadTimerAttempts = timeout; // seconds
setCookie(cookieName, 0, downloadTimerAttempts);
// set timer to check for cookie every second
downloadTimer = window.setInterval(function () {
var cookie = getCookie(cookieName);
// if cookie doesn't exist, or attempts have expired, re-enable form
if ((typeof cookie === 'undefined') || (downloadTimerAttempts == 0)) {
$("#" + buttonId).removeAttr("disabled");
$("#" + imageId).hide();
window.clearInterval(downloadTimer);
expireCookie(cookieName);
}
downloadTimerAttempts--;
}, 1000);
}
// form submit event
$("#btnSubmit").click(function () {
$(this).attr("disabled", "disabled"); // disable form submit button
$("#imgLoading").show(); // show loading animation
startDownloadChecker("btnSubmit", "imgLoading", 120);
});
<form method="post">
...fields...
<button id="btnSubmit">Submit</button>
<img id="imgLoading" src="spinner.gif" style="display:none" />
</form>
Supporting Javascript to set/get/delete cookies:
function setCookie(name, value, expiresInSeconds) {
var exdate = new Date();
exdate.setTime(exdate.getTime() + expiresInSeconds * 1000);
var c_value = escape(value) + ((expiresInSeconds == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = name + "=" + c_value + '; path=/';
};
function getCookie(name) {
var parts = document.cookie.split(name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
function expireCookie(name) {
document.cookie = encodeURIComponent(name) + "=; path=/; expires=" + new Date(0).toUTCString();
}
Server side code in ASP.Net:
...generate big document...
// attach expired cookie to response to signal download is complete
var cookie = new HttpCookie("DownloadCompleteChecker"); // same cookie name as above!
cookie.Expires = DateTime.Now.AddDays(-1d); // expires yesterday
HttpContext.Current.Response.Cookies.Add(cookie); // Add cookie to response headers
HttpContext.Current.Response.Flush(); // send response
Hope that helps! :)
You can fetch the file using ajax add indicator then create a tag with dataURI and click on it using JavaScript:
You will need help from this lib: https://github.com/henrya/js-jquery/tree/master/BinaryTransport
var link = document.createElement('a');
if (link.download != undefined) {
$('.download').each(function() {
var self = $(this);
self.click(function() {
$('.indicator').show();
var href = self.attr('href');
$.get(href, function(file) {
var dataURI = 'data:application/octet-stream;base64,' + btoa(file);
var fname = self.data('filename');
$('<a>' + fname +'</a>').attr({
download: fname,
href: dataURI
})[0].click();
$('.indicator').hide();
}, 'binary');
return false;
});
});
}
You can see download attribute support on caniuse
and in your html put this:
generate
I found the answer by jcubic worked really well for my needs.
I was generating a CSV (plain text) so did not need the additional binary library.
If you need to do the same, here is how I adjusted it to work for plain text files.
$('.download').on('click', function() {
// show the loading indicator
$('.indicator').show();
// get the filename
var fname = $(this).attr('data-download');
$.get("/products/export", function(file) {
var dataURI = 'data:text/csv;charset=utf-8,' + file;
$('<a>' + fname + '</a>').attr({
download: fname,
href: dataURI
})[0].click();
// hide the loading indicator
$('.indicator').hide();
});
});
The filename is specified with data-download attribute in HTML on the tag with .download class.

How to record the 301 Redirects URL?

I enter to browser this link
https://google.com.vn;
Google redirect to https://www.google.com.vn;
I want alert full url redirect.
I used this code:
processNewURL: function(aURI) {
var tabIndex = gBrowser.tabContainer.selectedIndex;
var referredFromURI = gBrowser.tabContainer.childNodes[tabIndex].linkedBrowser.webNavigation.referringURI.spec;
alert(referredFromURI);
},
But it always alert https://www.google.com.vn,
and I tested with some short link example bit.ly/R9j52J . It isn't ok.
Please help me.
this works, i also show 2 methods to get to webNavigation. the second method is just longed winded way to teach other stuff, recommended way is method 1.
var processNewURL = function(e) {
console.log('e:', e);
var win = e.originalTarget.defaultView;
//start - method 1 to get to webNav:
var webNav = win.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIWebNavigation);
var referredFromURI = webNav.referringURI;
//end - method 1
//start - method 2 long winded way:
/*
var domWin = win.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIWebNavigation)
.QueryInterface(Ci.nsIDocShellTreeItem)
.rootTreeItem
.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIDOMWindow);
var tab = domWin.gBrowser._getTabForContentWindow(win);
//console.log('tab:', tab);
var referredFromURI = tab.linkedBrowser.webNavigation.referringURI;
*/
//end - method 2
if (referredFromURI != null) {
win.alert('referred from:' + referredFromURI.spec);
} else {
win.alert('not redirected');
}
}
gBrowser.addEventListener('DOMContentLoaded', processNewURL, false);

Why am I suddenly not getting content from the Blogger API?

I have been using the Google API to get JSON data from my Blogger account and display and format blog posts on my own webiste.
It was working perfectly for weeks, and then suddenly, as of yesterday, the content stops displaying. The title, update (the date the post was updated), and the id, all come back just as they always have. Only the content stopped coming back.
I haven't changed the code in any way since first implementing it, and I looked for documentation to see if the API had changed, but didn't come across anything. So I am completely stumped as to why this one aspect of the code would suddenly stop working.
This is pretty much the entire Javascript that I use to get the JSON data. Is there something wroing with it?
function init() {
// Get your API key from http://code.google.com/apis/console
gapi.client.setApiKey('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
// Load the Blogger JSON API
gapi.client.load('blogger', 'v3', function() {
// Load the list of posts for code.blogger.com
var request = gapi.client.blogger.posts.list({
'blogId': 'xxxxxxxxxxxxxxxxxxx',
'fields': 'items(content,title,updated,id)'
});
request.execute(function(response) {
var blogger = document.getElementById("blogger");
var anchor = 0;
for (var i = 0; i < response.items.length; i++)
{
var bloggerDiv = document.createElement("div");
bloggerDiv.id = "blogger-" + i;
bloggerDiv.className = "bloggerItem";
$(bloggerDiv).append("<h2>" + response.items[i].title + "</h2>");
var date = response.items[i].updated;
date = date.replace("T", " ");
date = date.replace("+09:00", "");
var printDate = new moment(date);
$(bloggerDiv).append("<p><span class='byline'>" + printDate.format('dddd, MMMM Do YYYY, h:mm:ss a') + "</span></p>");
$(bloggerDiv).append(response.items[i].content)
bloggerAnchor = document.createElement("a");
bloggerAnchor.name = "blogger-" + response.items[i].id;
blogger.appendChild(bloggerAnchor);
blogger.appendChild(bloggerDiv);
anchor = anchor + 1;
}
// find out which anchor the user wanted...
var hashVal = window.location.hash.substr(1);
// ... then jump to that position:
location.hash = "#" + hashVal;
});
});
}
Now fetchBodies defaults is false instead of true. For this reason you need to add param fetchBodies=true.

Loading A text along with a picture using AJAX

I have made a photo gallery in my website using the following:
/*Begin Photo Gallery Code*/
var images = ['g1.jpg', 'g2.jpg', 'g3.jpg', 'g4.jpg'];
function loadImage(src) {
$('#pic').fadeOut('slow', function() {
$(this).html('<img src="' + src + '" />').fadeIn('slow');
});
}
function goNext() {
var next = $('#gallery>img.current').next();
if(next.length == 0)
next = $('#gallery>img:first');
$('#gallery>img').removeClass('current');
next.addClass('current');
loadImage(next.attr('src'));
}
$(function() {
for(var i = 0; i < images.length; i++) {
$('#gallery').append('<img src="images/gallery/' + images[i] + '" />');
}
$('#gallery>img').click(function() {
$('#gallery>img').removeClass('current');
loadImage($(this).attr('src'));
$(this).addClass('current');
});
loadImage('images/gallery/' + images[0]);
$('#gallery>img:first').addClass('current');
setInterval(goNext, 4000);
});
It loads one picture at a time from a set of four pictures. Also I have four html files, each of them being relevant to one of the pictures. I want to use JavaScript/JQuery/AJAX to load the relevant html file's content along with the shown picture. Does anyone have an idea how I can do this?
Should I put the ajax files (4 html files) into a JavaScript array or something?
var ajaxPages=['ajax1.html','ajax2.html','ajax3.html','ajax4.html'];
Thanks in advance.
Unless the HTML files supposed to change somehow during their displaying, should either output them via your server-side code in hidden divs with the request (would be the correct way of doing it) or use AJAX to save them in a variable or create hidden divs.
First you need two arrays like this:
var ajaxPages=['ajax1.html','ajax2.html','ajax3.html','ajax4.html'];//File Names
var divPages=['div1','div2','div3','div4'];//Div ids in order
For the AJAX part you should use something like:
var getHtml = function(filename,divid){
$.post('html/'+filename, function(data) {
//The first argument is your file location
//Second one is the callback, data is the string retrieved
$('#'+divid).html(data);
});
}
$.each(ajaxPages,function(index,value){
getHtml(value,divPages[index]);
});
That should do it... Do tell me if you require further explanation.
EDIT:
var ajaxPages=['ajax1.html','ajax2.html','ajax3.html','ajax4.html'];
var divId="yourdivid";
var textArray=new Array();
var currentImg=0;
var getHtml = function(filename){
$.post('html/'+filename, function(data) {
textArray.push(data);//Save data inside the array textArray
});
}
$.each(ajaxPages,function(index,value){
getHtml(value,divPages[index]);
});
Then your goNext() method:
function goNext() {
var next = $('#gallery>img.current').next();
if(next.length == 0){
next = $('#gallery>img:first');
currentImg=0;
}else{
currentImg++;
}
$('#gallery>img').removeClass('current');
next.addClass('current');
loadImage(next.attr('src'));
$('#'+divId).html(textArray[currentImg]);//Adds text to div based on current picture
}
That should be working fine!

Categories