javascript location.reload doesn't reload the page in a wrong way - javascript

I'm trying to refresh a page every time a user click the button so the page is set back to source code. but the location.reload() is executed after the code, and not at the beginning.
btn.addEventListener("click", () => {
location.reload()
//code...
}
Why does not reload the page immediately when the button is clicked, but only when the function ended?
Is there another way to set the page back to the source code?

why does not reload the page immediately when the button is clicked but only when the function ended?
Because JavaScript blocks navigation.
If it didn't, then the page would reload and the rest of the function wouldn't run at all (because the page it was running in has been destroyed and a new version loaded instead).
If you want to cause the page to reload and then a function to run on the new page, then you need to pass the instruction to run that function to the newly reloaded page (e.g. via sessionStorage).
When the page loads (e.g. wait for a DOMContentLoaded event), check for the instruction, act on it if needed, then delete the instruction so it won't trigger automatically next time the page loads from another mechanism).

This here seems to work but you would have to implement it in a way so that btnClicked is not always true to execute the other code. Wrapping it around the if to check 'true'. Then it reloads the page without going to the else. Setting the btnClicked to false will run the else code without reloading the page.
Hopefully this can give you an idea!
<!DOCTYPE html>
<html>
<body>
<button class="btn" >Click to reload page</button>
<p class="text">Original Text</p>
<script>
const btn = document.querySelector('.btn');
const text = document.querySelector('.text');
btn.addEventListener("click", () => {
var btnClicked = true
if(btnClicked == true){
location.reload()
} else {
text.innerHTML = 'New Text';
}
})
</script>
</body>
</html>

Related

How to run a php file without refreshing the web page?

I have a problem. It is my full honor if anyone helps.
First, let me explain the workflow I want. My CMS is Wordpress. I have a webpage (views.php). In this page, I want to show a download button (id=” download-button”) just to users who has the role subscriber. In default, no one has the role subscriber. So, the button is hidden in default. When a user buys a specific product he gains the role subscriber. Now, suppose a user has opened views.php page as a tab in his browser. In this step, the button is hidden. After that, he opens another tab and buys that specific product and he gains the role subscriber. Now, if he refresh the view.php page, the download button is seen. But, I want the user to see the download button without refreshing the page. In this regard, I wrote button.php file to be called in ajax. However, it does not work.
My codes:
html code (written in view.php which is the place of download button):
<div id="div1"></div>
my javascript code (which is put inside view.php file):
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").load("button.php");
});
});
</script>
my button.php code:
<?php
if (check_user_role(array('subscriber'))) {
echo ('<button id="download-button">Download</button>');
}
?>
I should note that I have written check_user_role php function in views.php.
It would be my honor if you help.
Thanks in advance.
Milad
As stated by smartdroid in one of the answers above, you can subscribe an event listener function to the window.onfocus event. Try following:
document.addEventListener("DOMContentLoaded", function (event) {
window.onfocus = function () {
$("#div1").load("button.php");
}
});
I highly recomment you to read further into javascript events.
For plain javascript:
https://www.w3schools.com/js/js_events.asp
For jQuery:
https://api.jquery.com/category/events/
Hey you have to use Window setInterval() Method, what this method does it will fire in background at your time interval set.
You can call your ajax code to set/show your button
setInterval(function(){
$("#div1").load("button.php");
}, 3000);
Make sure once you do add this button put return false so it wont execute again and again not to increase load on webpage.
$(document).ready event runs only once after the DOM is loaded. So this event will not fire unless page is reloaded.
If the user is buying a subscription in another browser tab and then returns to the original tab, windows.onfocus event will fire.
So you can use window.onfocus event to check for subscription every time view.php tab becomes active, and then show the button when necessary. So you can use something like the following, in your view.php
$(document).ready(function(){
window.onfocus = function () {
$("#div1").load("button.php");
}
});
Add an iframe to your view.php that doesn't need to contain anyting nor be visible.
<iframe name="download" id="if_download" src="blank.html"></iframe>
Target the download-action to the iframe. With some JS:
function download(href) {
window.frames['download'].location = 'download.php?file=' + href;
return false;
}
You may need to wrap the download-action through a php-file to modify its header
download.php:
$file_name = $_GET['file'];
//validate file exists and *remove any ../ - simple:
if (strpos($file_name, '/') !== false) die('yeah right..');
header("Content-Disposition: attachment;filename=\"$file_name\"");
echo file_get_contents($file_name);
die();

Why is my page not rendering the data I need when trying to page redirect in jQuery/JS?

The id's #switchtopagetwo and #switchtoindex are assigned to buttons that do what you can infer from the id's names. What I want to do is on click of the button, I want to redirect to the new page via window.location = url; and then run a function that renders some data on the page via pagetwoData() or pageoneData(), depending on where I am at the moment.
$('#switchtopagetwo').on('click', function () {
window.location = 'pagetwo.html';
pagetwoData();
});
//pagetwo.html button
$('#switchtoindex').on('click', function () {
window.location = 'index.html';
pageoneData();
});
When I comment out window.location, the functions run and I can see the data on the screen, but there's no page redirect even on clicking the button. When I click on the buttons fast enough, I can see the function's data being rendered for a split second and then disappearing. When I console.log certain items, I can see the console.log's appearing in the console and then disappearing the same way.
Clearly there is an issue with window.location. Is there better code I can use for clicking the button, redirecting the page to load the page-2 data, then clicking the button again to go back to page-1 data?
When you redirect to a new page, the entire page context is abandoned and replaced by the new page. Nothing which happens on the source page after that redirect can be relied upon to still happen. But anything on the target page that's loading will happen.
Instead of trying to get Page1 to tell Page2 to do something when it loads, just have that something happen on Page2. For example:
// on index.html
pageoneData();
$('#switchtopagetwo').on('click', function () {
window.location = 'pagetwo.html';
});
// on pagetwo.html
pagetwoData();
$('#switchtoindex').on('click', function () {
window.location = 'index.html';
});
Basically, for any given page, whatever you want to happen on that page when it loads should be executed on that page when it loads.

location.reload(), Javascript,HTML

I'm having a problem always when I try to use the following code in a button in my HTML file.
onClick=window.location.reload();
mapGenerator();
The page reloads but the javascript (mapGenerator) that make a D3JS view doesn't appear. What am I doing wrong?
location.reload() will immediately reload the page and prevent any following code to execute.
You can, however, create a function that executes your method after the page has (re)loaded:
window.onload = function() {
mapGenerator();
};
This method will run every time the page has fully loaded. To only run the code after you have reloaded the page using location.reload(), you could create a method that handles the click by setting a cookie and then reloading the page.
function handleClick() {
document.cookie="reload=true";
location.reload();
}
This would require you to change your onClick value to onClick="handleClick();". Now, whenever the page loads, you can check whether the cookie has been set. Your window.onload function now changes to this:
window.onload = function() {
if(document.cookie.indexOf("reload") >= 0) {
mapGenerator();
}
}
Checking if a cookie exists - answer by Michael Berkowski
After the reload it's up to you whether you want to unset the cookie — if you don't, the page will run the function mapGenerator on every page load until the cookie expires.
If you need more help with cookies, check out W3Schools' tutorial.
As per your description mentioned above two actions are to be taken on click. As the first action reloads the page the second action is lost. If you want any action to be taken on load of the page, mention the same on onload event of the page.

JavaScript Timers and Page Navigation

Hopefully a simple question; if I create a timer using JavaScript embedded within my page, and I then navigate away from that page, will the timer be automatically cancelled or will it continue to run?
EDIT
Expanding the question, if that page were to perform a post-back (in my case, this is ASP.NET Forms), and the script is rendered as a part of the page markup, would the original timer created when the form is first displayed be cancelled during that post-back or would a second timer be created?
Example (rough typed):
<body>
...
<script type='text/javascript'>
function doSomething() { ... }
x = setInterval(doSomething(), 60000);
</script>
...
<button type="submit" />
...
</body>
Following the post-back, a new timer will be created as a result of the page being re-rendered, how many timers are now running (assuming the post-back was within the interval specified by the timer)?
It'll be automatically cancelled. JavaScript code is executed within the context of a page.
Think about a page like an application. Switching to other page is like closing an application and opening a new one. This also applies to a full page refresh (i.e. when you press F5).

How to keep the innerhtml content that is changed with the JS onclick function

this is a simple problem but cant seem to solve it.
I want to be able to change the innerhtml content of a link, once is triggered by an onclick function triggered from separate link that actually takes the user to another page (inside the website not external site), I get the script to work but the desirred innerhtml content to be changed dissapears once the page reloads and goes to the other page the link is pointing to. I actually want to keep the change of the text change even if the page is reloaded and taken elsewhere.
The script looks like something like this:
<script>
function myFunction() {
document.getElementById("testchange").innerHTML = "Get Started";
} //Js script that does the innerHMTL change
</script>
eng // button that triggers the onclick function but takes the user to another page inside the site
<a href="http://example.com" id="testchange" >Hello</a> // text to be changed by JS and want to keep the change even if the page is reloaded and taken elsewhere
So any ideas how i could do that? Thanx
For this to work you need some kind of storage. Let's try localStorage:
You first check if the changes has been made before setting the variable, then handle your event:
<script>
function ready(fn) {
if (document.readyState != 'loading'){
fn();
} else {
document.addEventListener('DOMContentLoaded', fn);
}
}
}
function myFunction() {
document.getElementById("testchange").innerHTML = "Get Started";
//this will save the state of the change
localStorage.setItem('textSet', true);
}
//this will change the text when the page is loaded if the change has been made before.
ready(function(){
if(localStorage.getItem('textSet')){
document.getElementById("testchange").innerHTML = "Get Started";
}
})
</script>
Either use Cookies or Session/Local storage, sessionStorage option below
Data stored in sessionStorage will lasts as long as the browser window is open, whereas localStorage has no expiration time
eng
<a href="http://example.com" id="testchange" >Hello</a>
<script>
function setFlag() {
sessionStorage.setItem('setFlag', 'true');
}
if (sessionStorage.getItem("setFlag"))
document.getElementById("testchange").innerHTML = "Get Started";
</script>
Note: this code will need to be place after your HTML elements ideally at bottom of the page

Categories