Target page refresh either by javascript or PHP - javascript

I am trying to figure out how can I refresh a target page when visited either by a hyperlink or the back button, or even a button. Any ideas ? I have tried almost any solution I could find online and still can make the target page refresh after visited.

Well you can refresh the page using JavaScript with this code:
location.reload();
But if you don't put a condition on it, it'll refresh forever, right?
You'll need to describe your issue in more detail.

if you want to reload page when page full loaded use this JS:
$( document ).ready(function() {
location.reload();
});
if you want timer when page loaded and then reload it use:
$( document ).ready(function() {
// reload after 5 second
setTimeout(function() {
location.reload();
}, 5000);
});
if you want reload only first time use this:
function setCookie(cookieName,cookieValue,nDays) {
var today = new Date();
var expire = new Date();
if (nDays==null || nDays==0) nDays=1;
expire.setTime(today.getTime() + 3600000*24*nDays);
document.cookie = cookieName+"="+escape(cookieValue)
+ ";expires="+expire.toGMTString();
}
function getCookie(cookieName) {
var theCookie=" "+document.cookie;
var ind=theCookie.indexOf(" "+cookieName+"=");
if (ind==-1) ind=theCookie.indexOf(";"+cookieName+"=");
if (ind==-1 || cookieName=="") return "";
var ind1=theCookie.indexOf(";",ind+1);
if (ind1==-1) ind1=theCookie.length;
return unescape(theCookie.substring(ind+cookieName.length+2,ind1));
}
So, you would tie it together like this:
$(function() {
var skipModal = getCookie('skipModal');
if (!skipModal) { // check and see if a cookie exists indicating we should skip the modal
// show your modal here
setCookie('skipModal', 'true', 365*5); // set a cookie indicating we should skip the modal
}
});
show this link:
Fire jquery script on first page load, and then never again for that user?

Related

how to refresh the page with original URL when URL has been changed via history.pushState()

I have used history.pushState() and now if the user refreshes the page then it is refreshing current URL which is not an original URL.
I tried detecting refresh page with a cookie, hidden filed but it is not working.
window.onload = function() {
document.cookie="PR=0";
var read_cookies = document.cookie;
var s = read_cookies;
s = s.substring(0, s.indexOf(';'));
if( s.includes("1"))
{
window.location.href = "https://www.google.com";
}
else{
document.cookie="PR=1";
}
loadURL();
};
function loadURL()
{
document.cookie="PR=1";
document.getElementById("visited").value="1";
var str="abc/b cd";
str=str.replace(/ /g, "-");
history.pushState({},"",str);
}
when user is refreshing the page I need original URL on that time.
This might be helpful. But you need control over the pushed url.
// this goes to your 'original' url
window.addEventListener('beforeunload', function (event) {
sessionStorage.setItem('lastPage', window.location.href)
}
// page with your pushed url
if (sessionStorage.getItem('lastPage') === 'PAGE_YOU_DONT_WANT_TO_BE_REACHABLE_DIRECTLY') {
window.location = 'PAGE_YOU_WANT'
}
I'm interested what the use case for this is. As far as my knowledge goes you can't suppress the refresh event completely.

toggle button to start/stop refreshing my page

I'm trying to make sort of a toggle button to start and stop a page from refreshing itself but for some reason the stopping process isn't working. is my logic correct?
this is my code:
<button id = "toggleButton" onclick = "initRefresh()" > Stop Refresh </button>
<script>
function reloadUrl() {
window.location.replace(
[location.protocol, '//', location.host, location.pathname].join('')
);
}
function initRefresh() {
if ($('#toggleButton').text() == 'Start Refresh') {
$('#toggleButton').text("Stop Refresh");
t = window.setTimeout(reloadUrl, 45000);
} else {
$('#toggleButton').text("Start Refresh");
clearTimeout(t);
}
};
var t = window.setTimeout(reloadUrl, 45000);
</script>
the default option (on first load) is on. so when the user goes into the page for the first time 45 seconds later the page will refresh.
Thanks for the help.
I believe the problem comes from the initialization of the t variable.
You start a setTimeout when the page loads.
Change it to var t = null and the above code should work.
Your code (as in question) is working 100%.
But it will not work if placed your code inside $(document).ready event.

Show modal to user when updated

I have made this modal and it shows only on first visit to the website
$(document).ready(function(){
setTimeout(function(){
if(!Cookies.get('modalShown')) {
$("#myModal").modal('show');
Cookies.set('modalShown', true);
} else {
alert('You already saw the modal')
}
},1000);
});
In the modal it shows content of what new functionality to the application is added. So my target is to show the modal to the user every time I update the modal content. How can I do this?
You could use versionning in your cookies values :
var currentRelease = "1.0.1",
currCookie = Cookies.get('modalShown')
setTimeout(function(){
if(!currCookie || currCookie != currentRelease) {
$("#myModal").modal('show');
Cookies.set('modalShown', currentrelease);
} else {
alert('You already saw the modal')
}
},1000);
Note that this method forces you to update the value of "currentRelease"
you could also crypt the text content of the modal into md5 and use that value in your cookie, so whenever the modal value change, the md5 changes
So this is what worked for me:
$(document).ready(function() {
var currentRelease = document.getElementById("version").innerHTML;
var currCookie = Cookies.get('modalShown');
setTimeout(function () {
if(!currCookie || currCookie != currentRelease) {
$("#myModal").modal('show');
Cookies.set('modalShown', currentRelease);
}
}, 1000);
});
The id version is part of modal-content so as soon as I change something within the content the user will see the modal again on first visit since the change in the content.

Javascript change location href and click on a certain button

I would like to redirect the user onclick to a certain page "user/logged_in1" if the user is not already on that page and after the redirect a certain button must be clicked. This button opens a modal.
Doesn't work with this function:
function redirect_to_logged_in_and_open_modal() {
if(window.location.href.indexOf("logged_in") > -1) {
return
} else {
location.href="user/logged_in1";
document.getElementsByClassName("zimmerbtn")[0].click();
}
}
It seems it searched already for the button before the redirect happens and therefore the list is empty. How to fix this?
EDIT
This is a little bit more complex. The modal should only open if the user uses the redirect. If I use onload on the body tag, the modal will always open if the page is loaded, I don't need that. I need that modal only to be opened if the redirect happens.
The whole thing is a Python flask application:
{% if current_user.zahlung_iban == None and have_this_user_a_room != None %}
<li><a class="btn mybtn" onclick="redirect_to_logged_in_and_open_modal()" data-toggle="modal" data-target="#premium-special-modal"> Zimmer anbieten </a></li>
{% else %}
<li><a class="btn mybtn" href="{{ url_for('zimmer_einstellen') }}"> Zimmer anbieten </a></li>
{% endif %}
As you see there is a certain trigger for the button to become the redirect button.
EDIT
Okay working with a cookie sounds like a possible solution. But I cant figure out how to delete the cookie after the button was clicked, none of the proposed code works, eventhough it looks simple:
function redirect_to_logged_in_and_open_modal() {
if(window.location.href.indexOf("logged_in") > -1) {
return
} else {
location.href="user/logged_in1";
document.cookie = "redirected_coz_of_click";
}
}
$( document ).ready(function() {
if ($(".logged-in-container")[0]) {
var delete_cookie = function(name) {
document.cookie = name + '=;expires=Thu, 01 Jan 1970 00:00:01 GMT;';
};
if (document.cookie.indexOf('redirected_coz_of_click') > -1 ) {
document.getElementsByClassName("zimmerbtn")[0].click();
delete_cookie('redirected_coz_of_click');
console.log(document.cookie);
} else {
console.log("cookie removed");
}
}
});
1: Append a parameter to the redirect url
user/logged_in1?click=btn_id
2: On landing on that page you can then check if the parameters is there. Found this method
var getUrlParameter = function getUrlParameter(sParam) {
var sPageURL = decodeURIComponent(window.location.search.substring(1)),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : sParameterName[1];
}
}
};
Found the method here: https://stackoverflow.com/a/21903119/3514785
So you could use it like this:
var btnToClickId = getUrlParameter("click");
3: With jquery (or javascript if you want) fire the click event on that btn:
$("#"+btnToClickId).click();
NB: You want to do the check after the page has loaded:
$(window).on("load",function() {
var btnToClickId = getUrlParameter("click")
if(btnToClickId) {
$("#"+btnToClickId).click();
}
});
So in summary
a: Edit your page and remove this line document.getElementsByClassName("zimmerbtn")[0].click(); because it is pointless
b: In the target page in the js copy and past the `getUrlParameter' method.
c: Then inside a on window load event listener do the url check as specified in 3.
ALTERNATIVE TO URL PARAMETER
You could instead use localStorage or some cookie to store the target id right before redirecting. Make sure you remember to clear it in the target page after grabbing it so that it is not always triggered even when you have not redirected from the page that triggers this whole process.
You can not access elements that have not even loaded yet.
By using location.href = '' you are simply directing a user to a page, any javascript after will fail because the page hasn't been loaded yet.
You tell us that you want to redirect a user to a page onclick. This sounds like the essential of an anchor tag:
Click Me
For step 2, just place the javascript on the page you are redirecting to. Bind to the load event of the page and then execute your javascript:
window.onload = function() {
document.getElementsByClassName("zimmerbtn")[0].click();
};
You can use cookie.
Set cookie when user click on the redirect button and when page is loaded, check if the cookie is set and open the modal. When you done with opening the modal clear the cookie. In that way you can easily achieve this.
Instead of triggering click. Call the onclick function in body onload method of user/logged_in1.
<body onload="openModal()">
You are trying to access a content on your initial page, but you have already redirected the user from that page, so this cannot be achieved by the current method.
I believe what you are trying to do is to open up a modal, after redirecting, do the following.
On your redirected page add the following, use jquery to achieve this
$( document ).ready(
// add the functionality to launch modal here
);
I created an onclick() function for this button:
onclick="redirect_to_logged_in_and_open_modal()"
In the function I check if I am not already on the logged_in site. If not I redirect but I add an additional parameter to the URL ?redirected.
In the next step if the logged_in is loaded and the parameter is in the URL the modal will also open, thats it.
Thanks #Zuks for the Idea adding a param to URL.
function redirect_to_logged_in_and_open_modal() {
if(window.location.href.indexOf("logged_in") > -1) {
return
} else {
window.location.assign("https://www.example.com/user/logged_in1?redirected");
}
}
$( document ).ready(function() {
if ($(".logged-in-container")[0]) {
if(window.location.href.indexOf("redirected") > -1) {
document.getElementsByClassName("zimmerbtn")[0].click();
}
}
});

Event before loading ajax content

I am trying to maintain few objects in cookie to restore some settings. Initially i tried in window.unload to save and restore settings using cookie.It worked in full page load. But it didn't work in my case as whole page is not loading just replacing the specific content using ajax post(ajax load). So can you tell me in which event can i save those values in cookie to restore back while using ajax post ?
I tried the below code in window.unload event
window.onunload = function (e) {
var gridObjModel = $("#Grid");
var myCookie = escape(JSON.stringify({
"CurrentPage": gridObjModel.pageSettings.currentPage,
"SortedColumns": gridObjModel.sortSettings.sortedColumns,
"GroupedColumns": gridObjModel.groupSettings.groupedColumns
}));
document.cookie = myCookie;
}
You could try with the following:
$(window).on("unload", function (e) {
var gridObjModel = $("#Grid");
var myCookie = escape(JSON.stringify({
"CurrentPage": gridObjModel.pageSettings.currentPage,
"SortedColumns": gridObjModel.sortSettings.sortedColumns,
"GroupedColumns": gridObjModel.groupSettings.groupedColumns
}));
document.cookie = myCookie;
});
When you do a ajax load just trigger unload before:
$(window).trigger("unload");
$("#foo").load(someUrl);

Categories