34

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 !");
            }
        })
    })
2
  • try using location.href = document.referrer.
    – VPK
    Commented Sep 3, 2014 at 8:10
  • Redirect with a flag in the url that the previous page can recognise, then trigger a refresh if it's present on the previous page.
    – Novocaine
    Commented Sep 3, 2014 at 8:13

13 Answers 13

50

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.

3
  • window.location = document.referrer; did the job, thank you!
    – burkay
    Commented Mar 28, 2018 at 15:14
  • 1
    In your html, use <a href="#" onclick="GoBackWithRefresh();return false;">BACK</a>
    – alextc
    Commented Jun 28, 2018 at 6:27
  • window.location = document.referrer doesn't reload the page in current Firefox v70.
    – Forza
    Commented Nov 7, 2019 at 12:33
29

This is the correct answer. It will refresh the previous page.

window.location=document.referrer;
0
15

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");
3
  • i will try that, but it's not easy, in my url there is an ID. The value of this ID, change between the first page and the form page. I think that i can get it with localstorage
    – Julien698
    Commented Sep 3, 2014 at 8:22
  • you can pass parameters with this: window.location.replace("pagehere.html?id=1");
    – user3493928
    Commented Sep 3, 2014 at 8:38
  • 3
    The better option without extra coding: window.location.replace(document.referrer); Tested on chrome, safari, firefox, edge.
    – gtamborero
    Commented Jan 23, 2020 at 11:51
14

Try these ...

Option1

window.location=document.referrer;

Option2

window.location.reload(history.back());
1
  • 5
    i found window.location.reload(history.back()); doesn't work as expected - refreshes to current (not previous) page Commented Jan 29, 2018 at 19:45
8

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.

0
7

I know this post is old but this can help.

window.location.replace(document.referrer);
1
  • 3
    This was the only thing that worked reliably for me. Commented Apr 29, 2022 at 4:48
4

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.

1

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

0

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('^');
 })
0

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.

0

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');
});
0

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");
0

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>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.