Reputation: 716
I have a problem in my code. The aim is to complete a simple form, when the user clicks on a submit button. It does an Ajax request. After the Ajax request succeeded, I use windows.history.back()
to go to the previous page and here I want to refresh this page, to refresh values which were modified by the form. Have you any 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 !");
},
});
});
Upvotes: 34
Views: 180495
Reputation: 1
I know this thread is old but the code never changes. So I'd like to contribute with a solution.
Put this on the page you want to refresh itself when you go back.
<!-- Refresh with the new changes made -->
<script type='text/javascript'>
window.addEventListener("pageshow", function (event) {
var perfEntries = performance.getEntriesByType("navigation");
if (perfEntries[0].type === "back_forward") {
location.reload(true);
}
});
</script>
Upvotes: 0
Reputation: 399
Just to disable http cache from server like this(php code).
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
Upvotes: 0
Reputation: 1
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');
});
Upvotes: 0
Reputation: 11
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
Upvotes: 1
Reputation: 153
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.
Upvotes: 0
Reputation: 141
I know this post is old but this can help.
window.location.replace(document.referrer);
Upvotes: 8
Reputation: 41
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.
Upvotes: 4
Reputation: 3291
This is the correct answer. It will refresh the previous page.
window.location=document.referrer;
Upvotes: 28
Reputation: 6858
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:
<a href="#" onclick="GoBackWithRefresh();return false;">BACK</a>`
For more customization you can use history.js plugins.
Upvotes: 50
Reputation: 783
Try these ...
Option1
window.location=document.referrer;
Option2
window.location.reload(history.back());
Upvotes: 14
Reputation: 836
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.
Upvotes: 8
Reputation: 1662
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('^');
})
Upvotes: 0
Reputation:
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");
Upvotes: 15