I've a probleme in my code. The aim is to complete a simple form, then you click on a submit button. It do an Ajax resquest to go in the method. On success in the ajax request, i use windows.history.back() to go to the previous page ans here i want to refresh this page, to refresh values which are modificated by the form ! Have you an idea about that ?
$('#form_edit').submit(function (e)
{
e.preventDefault();
$.ajax({
url: $('#form_edit').attr('action'),
type: 'POST',
cache: false,
data: $(this).serialize(),
success: function (data) {
if (data === true) {
alert("Modification réussie !");
window.history.back();
location.reload(); <= on success i want to refresh previous page
}
else {
alert("Modification échouée !");
}
},
error: function ()
{
alert("Modification échouée !");
}
})
})
window.history.back(); Sometimes it's an issue with javascript compatibility with ajax call or design-related challenges.
I would use this below function for go back with the refresh.
function GoBackWithRefresh(event) {
if ('referrer' in document) {
window.location = document.referrer;
/* OR */
//location.replace(document.referrer);
} else {
window.history.back();
}
}
In your html, use:
BACK`
For more customization you can use history.js plugins.
This is the correct answer. It will refresh the previous page.
window.location=document.referrer;
It will have already gone back before it executes the reload.
You would be better off to replace:
window.history.back();
location.reload();
with:
window.location.replace("pagehere.html");
Try these ...
Option1
window.location=document.referrer;
Option2
window.location.reload(history.back());
You can't do window.history.back(); and location.reload(); in the same function.
window.history.back() breaks the javascript flow and redirects to previous page, location.reload() is never processed.
location.reload() has to be called on the page you redirect to when using window.history.back().
I would used an url to redirect instead of history.back, that gives you both a redirect and refresh.
I know this post is old but this can help.
window.location.replace(document.referrer);
After struggling with this for a few days, it turns out that you can't do a window.location.reload() after a window.history.go(-2), because the code stops running after the window.history.go(-2). Also the html spec basically views a history.go(-2) to the the same as hitting the back button and should retrieve the page as it was instead of as it now may be. There was some talk of setting caching headers in the webserver to turn off caching but I did not want to do this.
The solution for me was to use session storage to set a flag in the browser with sessionStorage.setItem('refresh', 'true'); Then in the "theme" or the next page that needs to be refreshed do:
if (sessionStorage.getItem("refresh") == "true") {
sessionStorage.removeItem("refresh"); window.location.reload()
}
So basically tell it to reload in the sessionStorage then check for that at the top of the page that needs to be reloaded.
Hope this helps someone with this bit of frustration.
I know this is pretty old but I thought my answer would help someone as most of codes here refreshed current page not previous one
so you can't get back to previous page and refresh it at same time as JS will run the code that takes you back and stops (will not run refresh page part) so I found a way to combine both functions
window.location.assign(window.history.back());
This basically will load a "new page" (so it will refresh it) but at same time it will load the previous page in browser history
window.history.back() does not support reload or refresh of the page. But you can use following if you are okay with an extra refresh
window.history.back()
window.location.reload()
However a real complete solution would be as follows:
I wrote a service to keep track of previous page and then navigate to that page with reload:true
Here is how i did it.
'use strict';
angular.module('tryme5App')
.factory('RouterTracker', function RouterTracker($rootScope) {
var routeHistory = [];
var service = {
getRouteHistory: getRouteHistory
};
$rootScope.$on('$stateChangeSuccess', function (ev, to, toParams, from, fromParams) {
routeHistory = [];
routeHistory.push({route: from, routeParams: fromParams});
});
function getRouteHistory() {
return routeHistory;
}
return service;
});
Make sure you have included this js file from you index.html
<script src="scripts/components/util/route.service.js"></script>
Now from you stateprovider or controller you can access this service and navigate
var routeHistory = RouterTracker.getRouteHistory();
console.log(routeHistory[0].route.name)
$state.go(routeHistory[0].route.name, null, { reload: true });
or alternatively even perform checks and conditional routing
var routeHistory = RouterTracker.getRouteHistory();
console.log(routeHistory[0].route.name)
if(routeHistory[0].route.name == 'seat') {
$state.go('seat', null, { reload: true });
} else {
window.history.back()
}
Make sure you have added RouterTracker as an argument in your function
in my case it was :
.state('seat.new', {
parent: 'seat',
url: '/new',
data: {
authorities: ['ROLE_USER'],
},
onEnter: ['$stateParams', '$state', '$uibModal', 'RouterTracker', function($stateParams, $state, $uibModal, RouterTracker) {
$uibModal.open({
//....Open dialog.....
}).result.then(function(result) {
var routeHistory = RouterTracker.getRouteHistory();
console.log(routeHistory[0].route.name)
$state.go(routeHistory[0].route.name, null, { reload: true });
}, function() {
$state.go('^');
})
Brandon Hoult answered of Dec 18, 2019 at 3:33
I didn't get at at first but YES, it works! via session variable flag, but I'll say it it backwards
Set this in the page you want to be refreshed if user goes back to it with history back or browser back.
if (sessionStorage.getItem("refresh") == "true") {
sessionStorage.removeItem("refresh"); window.location.reload()
}
Set this flag in the page you make changes like the shopping cart or the ajax mentioned that will change stuff, some setttings, classes, etc.
sessionStorage.setItem('refresh', 'true');
My case:
I hard code settings in a buy page while loading it, like prices and class of buy buttons: "add" or "in cart" icons. User adds an item to cart, then I add the product calling ajax and change that button's class to "in cart". If user wants to remove it from cart just clicks the cart icon and ajax again to remove it from cart and change class to "add".
Problem:
User goes to cart page itself, see the products and decide to go back and page show old buttons icons because is history (first loaded page, not changed one) so need to reload the show updated info.
Solution above does:
Buy page will reload if user goes to cart and back since cart page set a session variable "refresh" and buy page checks if "refresh" = true, set refresh it to false (so only cart page can set refresh to true and refresh the page.
Session variable "refresh" is a name so you can call it whatever else so you can use as many different flags as you want.
step 1: save the referrer URL in the local cache on load functions.
$(function () {
let refUrl = document.referrer;
let origin = location.origin;
if (refUrl.replace(origin, '') !== location.pathname) {
localStorage.setItem("history", refUrl.replace(origin, ''));
}
});
step 2: redirect the page to the referrer URL on link click.
$('body').on('click', '.lnkRurl', function () {
location.href = localStorage.getItem('history');
});
Related
I am trying to make.. "something" to know if an user is closing the browser or in other case is idle. I need to logout the user using a token.
I am using Symfony2.4 and actual logout include a handler because I need to know if the person is logged in another computer. I can't simple use a session expire because that handler will not execute and the application will still show the user as logged.
I am using this code and works really good!!
<script>
var unloaded = false;
$(window).on('beforeunload', unload);
$(window).on('unload', unload);
function unload(){
if(!unloaded){
$('body').css('cursor','wait');
$.ajax({
type: 'get',
async: false,
url: "{{ logout_url('main') }}",
success:function(){
unloaded = true;
$('body').css('cursor','default');
},
timeout: 50
});
}
}
</script>
The thing with this is that when the user try to go any link in the website this code execute and they need to log in again.
What can I do to avoid this code run by simply going to another link or what other thing can I do to have similar results?
This is more of a Javascript question, but well.
What about wrapping all your external links with javascript that sets a flag that disables your unload() function ? This is not very smart to do, though, but should work.
Something like that (not tested) :
$('a').click(function(){
// set the flag
myFlag = true;
return true;
}):
and in your unload :
function unload(){
if (myFlag) {
myFlag = false
return
}
// the rest here
}
EDIT :
If you want to send a request on page unload, it's better to use navigator.sendBeacon() as the data is transmitted asynchronously to the web server when the User Agent has an opportunity to do so, without delaying the unload or affecting the performance of the next navigation. See https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon
In my app, I require to user to not use the back button of the browser on the last page. For that I find a way to replacing existing url with current page url. so user will stay with same page.
I am using this JS code :
init(){//writing at init
history.pushState(null, null, document.URL);
window.addEventListener('popstate', function () {
history.pushState(null, null, document.URL);
});
},
But what is the correct code of ember to replace the above code? what is the correct way to do?
thanks in advance.
You can prevent the user from transitioning to another route within your application by aborting any transition made from the willTransition hook of your last page's route. Add something like
actions: {
willTransition(transition) {
transition.abort();
}
}
to your last page's route
I am using the history.pushState to change the content of a page with ajax request.
And its very certain that after a history.pushState, the forward button is disabled in the browser so definitely any button that would be clicked will be the back button.
So I want to go back to the main state of the page before the pushState. I use ajax request to retrieve the contents of the main state but the problem is that how can I make the url in the browser go back to the main url. I don't want to use the pushState method for this due to some issues
I increment a value by one after ever ajax success in other to know how far I have pushState.
var mainState;
var pushed = false;
$('a').click(function(){
$.ajax({
url: "/path/to/content",
success: function(data){
$('div').html(data);
history.pushState('state', 'title', 'url');
mainState ++;
pushed = true;
}
})
})
window.onpopstate(function(){
if(pushed){ //knowing fully well that the forward button is disabled
// take it back to the main state
history.go(-mainState);
}
})
Let's say the mainState is 3 and I click the back button instead of going to the mainState it takes me to mainState - 3.
Please anyone know I can do this?
var mainState = 3;
-mainState; //-3
--mainState; //2
Your code should look like this
window.onpopstate(function(){
if(pushed){
history.go(--mainState); //FIXED
}
})
I'm trying to get the parameters of my search criteria into the url so that it's possible to copy and paste the specific search.
Currently I have this:
// Search criteria in the url
var ready = function(e){
$("#filterrific_filter").click(function(){
$.get($("#filterrific_filter").attr("action"), $("#filterrific_filter").serialize(), null, "script");
history.pushState(null, document.title, $("#filterrific_filter").attr("action") + "?" + $("#filterrific_filter").serialize());
e.preventDefault();
});
$(window).bind("popstate", function() {
$.getScript(location.href);
});
};
$(document).ready(ready);
$(document).on('page:load', ready);
The problem is: when a result is clicked on, and the users tries to go back to the search page again, they don't get back, they stay on the same page. The url changes though.
Here is a video to display the problem
And here is a link to the webpage, if you would like to test it yourself
Thanks in advance!
Try removing this whole section:
$(window).bind("popstate", function() {
$.getScript(location.href);
});
Since your apartments#show action (a guess, assuming you're using a RESTful design in your Rails backend) is a round-trip request (not AJAX, like your filter), and your query string URL will run the filterrific scripts correctly on a reload, you might as well let the back button work the default way.
Disclaimer: this is a shot in the dark without more context. If it doesn't work for you, and you provide more context, I'll happily revisit.
This is similar to, but not the same as How can I refresh a page with jQuery?:
I bring up a modal form that collects some stuff from the user and passes it off to the server via a $.ajax() call. The server sends back a path that should become the new window.location of the browser. So the ajax call wants to be something like:
$.ajax({
// stuff
success: function (destination) {
// other stuff
window.location = destination;
}),
// still more stuff
});
This works fine as long as destination is a pure path, like /some_path and if the browser is not currently on that page. However, if the path is the page that I'm currently on and also includes a target -- /some_path#some_target, I lose: the browser simply repositions the page at the specified target, but does not hit the server for a fresh view of the page, which I need (since the server has done some stuff during the ajax call).
So, maybe I just add a location.reload() after the window.location call? That would work when the code is running on the page to which it's being returned, I think. But if I'm on another page, I get hit by a race condition, where the reload is called before the browser has finished making the window.location change, and I get the old page reloaded, not the new destination.
Blurgh. Is there any way around this?
One approach would be to check if window.location.pathname (which is the path without # or ?) is the same as destination within your success callback:
success: function (destination) {
// other stuff
if (destination === window.location.pathname) {
window.location.reload(); // reload if we are on the same page
} else {
window.location = destination; // otherwise, navigate to "other" page
}
}),
window.location.reload() reloads the current page with POST data, while window.location.href=window.location.href does not include the POST data.