Refreshing page via JS snippet - javascript

While testing a way in Firefox to reload an HTML page without caching, I've included the following snippet in my code:
<script>
window.setTimeout(function () {
location.reload(false);
}, 5000);
</script>
This reloads the page after 5 seconds, however I get shown the prompt: "To display this page, Firefox must send information that will repeat any action (such as a search or order confirmation) that was performed earlier."
If there a way to do a silent refresh via Javascript, one that doesn't show any prompt? For instance, if I used the refresh Meta tag (HTML), my browser silently refreshes. I want to approximate that same experience, but via JS (and no cache). BTW mine is a Django web app, and I inject the JS code in my Django template.

This is standard behaviour to protect people from submitting form information more than once (eg, prevent double payments in an ecommerce system). Try telling the Javascript to direct to a 'new' page:
Try using this, setting the url to your own;
window.location = "my.url/index.html?nocache=" + (new Date()).getTime();
Answer borrowed from here where there is also an explanation given for why this works -> How can I force window.location to make an HTTP request instead of using the cache?

Have you tried location.reload (true) ? If set to true, it will always reload from server. Set to false it'll look at the cache first.

You are getting this prompt because you ask to reload a POST request. You should always get this prompt when reloading a POST request, as it is not a safe method
However, if you wish, you can explicitely resend a POST request (though you might have difficulties to find back the POST data previously sent). Or explicitely send a GET request to the same URL.

Related

Javascript reload page from server (2021)

I set a cookie with Javascript. I have a input type checkbox that will switch theme on the website from normal to classic version and so will the cookie name. My backend is PHP. I want to access the newly changed value when clicking the checkbox with PHP, so naturally i want to reload the page so PHP can pick up the new value. Here comes the problem, all the suggestions out there suggest this:
location.reload(true);
But my Visual Studio Code says this is deprecated and indeed, it does not work indeed.
I checked MDN - [https://developer.mozilla.org/en-US/docs/Web/API/Location/reload][1] and it says that i should not pass any params and just use
location.reload();
And yes, using this reloads the page but it seems like it doesn't reload it by requesting the page from the server because my PHP does not pick up the new value. Only when i hit the refresh button manually, it does. And MDN says "The Location.reload() method reloads the current URL, like the Refresh button." which doesn't seem true.
So what can i do here?
You can try reloading page from php using:
header("Location: *your directory*");
If you set the same page you were it will just reload.

After Redirecting to a page after loading another page

Currently I have a page that when you fill out a text box and click a button, it redirects you to another page.
The page needs to be loaded, since it updates and shows xml. (I cannot currently change how this is)
However what I what to do is after page was redirected once, redirect it again or just load another page in general.
The thing to note about the xml link, is that part of it is created with the text box, so it will be dynamic.
I currently have something along the lines of this
//please note that username is a textbox, I've just left it out
<script runat = "server">
void Button_Click(Object sender, EventArgs e)
{
var url = "http://website.com/scripts/" + username.text "/value/0"
try
{
Response.Redirect(url, true);
}
catch(Exception ex)
{//From what I learnt, adding true to redirect throws an exception,
//which is how I tried executing another redirect, but it doesn't seem to
//to load the first direct, and skips straight to this, I also put this
//in finally, because it seemed more appropriate to no avail
Response.Redirect(someurl, true);
}
}
So I'm wondering if this is actually possible, I also wonder if I'm just looking up the wrong keywords to find a solution.
I've spent a bit of time on this, and have yet to come to some sort of solution, but I'm new to web development so I may just be missing some incredibly simple.
Also I only really understand how C# works in asp, but am willing to learn how to add in javascript or VB if necessary.
Thanks in advance for the help
Edit: Solution!
So I managed to use javascript to append the textbox value to the xml link, request it and without showing the user (showing the user, is not necessary in this case).
After which a popup confirms that it is successful then reloads the page.
it is very self explanatory but what I did was
url = "website";
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", url, true);
window.alert("success");
return true;//this reloads the page, that or just window.location.reload();
For an added check, I will see if I can verify that the username is a valid username, and popup with failure text if not.
You seem to have a misunderstanding about what Response.Redirect(...) actually does. The method name is, in my opinion, a bit misleading. It suggests that somehow the Response to the currently executing request will be sent somewhere else than the requesting browser. This is not the case. The name could as well have been Response.SendRedirectResponseToBrowser, because that's what Response.Redirect does.
So when you do Response.Redirect(url) you are telling the server that is executing your page that is should send a response to the browser, telling the browser to do a GET request of the supplied url. The browser will then do that, at which point that page needs to include a separate Redirect in order to further tell the browser where to go next.
In this case then, the page at "http://website.com/scripts/" + username.text "/value/0" needs to be patched up so that after processing the request, it will also send a redirect response with the url you want to display next.
If you have no control over that page, then you must solve this some other way. Some options:
Use ajax to request the "http://website.com/scripts/" + username.text "/value/0" url. Then after completion set the page location to the url you want to show next.
Open the http://website.com/.... url in a _blank target, then set to location to the next page.
Use System.Net.Http.HttpClient in your code behind method to request the http://website.com/.... url, then do a redirect. This means that the server requests the url as part of processing the button click.
Notes:
If the http://website.com/.... url updates some state (like store some changes in a database or similar), then you should request it using a POST request, not a GET. GET requests can get a cached response which means that the server might never actually see the request, and therefore not do any processing.
Piecing together the url like this "http://website.com/scripts/" + username.text "/value/0" looks risky. You should at the very minimum url encode the username.text - HttpUtility.UrlEncode(username.text). Better yet would be the first validate that the entered username is actually a valid user name.
You can add a Refresh header (not a meta-refresh element) to the response that contains the XML. In the header, you can specify another URL and the number of seconds to wait before redirecting.
I guess it should be using JavaScript (front-end) instead of back-end error handling, because it goes to another page. Use promise to handle exception

Execute JavaScript on Django Page through URL without reload

i have a webpage that loads certain JavaScript packages.
www.mySite.com
If i enter JavaScript commands in the browser console, i am able to interact with them.
Lets take
alert('5')
as a simple example.
I would like the same JavaScript calls to be executed without the browser console but through a specific URL like:
www.mySite.com/?value=5
so that this leads to an execution of my JavaScript commands?
Without the Page beeing reloaded/refreshed but staying in the actual state.
My approach was to catch the extended URL in my Django View and execute the JavaScript command.
View:
class ShowPage(View):
def get(self, request, caseId):
value = request.GET.get('value', '')
if(value is not ''):
// execute JavaScript here...
return HttpResponse("<script>alert(" + value + ")</script>")
else:
...
return render(request, 'template.html', context)
But this leads to a loss of my page where i entered the URL.
Does anyone has an idea how to preserve the actual Browser content?
So that it is possible to call the loaded Javascript packages?
Another idea was to call JavaScript through Ajax. But how do i map a URL in Django to a Ajax request?
Your current code is problematic on many levels, particularly because it allows the user to execute arbitrary JS on your page. This is called a Cross-site Scripting (XSS) attack.
Another issue is that you seem to want to add a GET parameter without "changing the state" of the page. Here you must remember that a GET request is, by definition, a communication between the client and server. You can artificially change what the URL looks like using JS, but you cannot submit a GET request on the same page without reloading it.
This is why you certainly want to use AJAX, which allows you to fetch the contents from another page and return them to the current page in the background. Usually this is done by creating a view that returns a JsonResponse (in Django 1.7+) (see Creating a JSON response using Django and Python).
A simplified example would be to encode a view that simply displays some text. You could then retrieve this text using AJAX (I recommend the jQuery for this--it's simple and well-documented) and do whatever you want with it, including alert it.
Try to use a '#':
www.mySite.com#command
This doesn't reload the site.
Maybe this helps too:
url: https://css-tricks.com/snippets/javascript/get-url-and-url-parts-in-javascript/
url: Get current URL in web browser
'#': http://www.w3schools.com/html/html_links.asp
EDIT:
use 'eval()' to execute the input:
http://www.w3schools.com/jsref/jsref_eval.asp

window.location.reload(true) working inconsistently

I've been working on an automatic log-out functionality for my web page. As a part of that, I implemented the window.location.reload(true) in 3 different places in my code. Two of them are automatic, one is attached to a link. The link always works, but the automatic ones don't always work, and I don't understand why.
For the automatic logouts, one set by a debouncer:
var userActionTimeout = debounce(function(e) {
console.log("inaction timeout, reloading page");
window.location.reload(true);
},15000;);
$(document.body).on('mousemove keydown click scroll',userActionTimeout);
Which theoretically should reload the page after a certain amount of inactivity.
The other two uses happen after certain types of AJAX data submission (e.g. blatantly wrong data sent that could only happen if the client was modified) trigger a log out. Of course, any further AJAX submissions are ignored by the server, and the next page the server will serve the client is a login page. In the event this happened inadvertently, AJAX sends the client an error message that includes the following:
refresh to continue session
I also implemented a timeout that also happens if this link is served, which happens after the AJAX response is received:
if (typeof response._forceRefresh !== 'undefined' && response._forceRefresh) {
console.log('reload firing');
/*
some code to insert the link into a spotlight here
*/
setTimeout(function(){console.log('reloading in 3s...');},7000);
setTimeout(function(){
console.log('reloading...');
window.location.reload(true);
},10000);
}
However the issue I'm having is this: Most of the time, the debounce page reload works (tested in firefox & chrome), however occasionally it doesn't. The link always works, but the AJAX response reload is about 50/50. I know it receives the response from the server since the link shows up, but quite often it doesn't actually automatically reload the page.
What is going on?
When ever I get inconsistency on a web page, it usually involves caching that I didn't realize was happening. If you haven't already, look through your project with that in mind and see if there is an effected location that you can force it not to cache a page.
Another idea might be to try using the meta refresh element. There is another thread where this is suggested: auto logout idle timeout using jquery php

How can I refresh a webpage without the browser asking if I want to resend again

I got the following code to refresh my webpage. It works great if I don't submit anything with POST but if i do, i get a message from the browser when my webpage refreshes (see image below)
location.reload(true);
I'm not looking for the browser settings tweak. I'm looking for alternative code to refresh without asking.
This is caused due to the page being requested by POST instead of GET. Refreshing will resubmit the POST data. You can force a get using window.location = window.location.href;.
If you want to allow people to reload the page through their browser controls then you will need to implement the PRG pattern which redirects to a GET after a POST.
This will request for a page and not a reload.
window.location = window.location;
GET vs. POST
The solution: don't POST. GET is supposed to be idempotent (up to environmental changes), POST is supposed to be a modification.
After the POST, you should be performing an immediate GET to reload the page with the result of the POST. Then you can refresh at will.
Example:
page_1.html
<form method="POST" action="go.php"> ... </form>
go.php:
<?php
// do stuff...
header('Location: http://www.foo.com/page2.html');
?>
page2.html:
<script type="text/javascript"> location .reload (true); </script>
This is controlled on the browser end and not yours (ie you CAN'T control it). If you want to show the user a page that can be refreshed without the repost option, you'll have to do it via a redirect following the post to a page that you retrieve with a GET not a POST.
Try a javascript redirect. Or alternatively, POST the information using AJAX which will mean refresh reloads the original page, not the results of your ajax post.
you can save your data to window.name and use the window.location = window.location.href trick. and when onload, check if you have data in window.name, get it back and remove it from there. i use the window.name as "session" storage quite often for situations like this.
(I'm spanish speaker, I´ll do my best)
In my case, I have a button to looking for open tickets in a DB, so, i need to press that button every time that I wanna know if there are new ones, I resolved with the next javascript function
<script type="text/javascript" language="javascript">
setTimeout('document.getElementById("btn_busca_ticket").click()', 10000);
</script>
where 10000 is the time between every refresh, (10 seconds)
if you don't have a button, you can create a hidden one with an ID and a submit
(it's not so elegant, but works for me)

Categories

Resources