[javascript] Windows.history.back() + location.reload() jquery

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 !");
            }
        })
    })

This question is related to javascript jquery ajax

The answer is


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

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.


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

Try these ...

Option1

window.location=document.referrer;

Option2

window.location.reload(history.back());

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.


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.


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

window.location=document.referrer;

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to ajax

Getting all files in directory with ajax Cross-Origin Read Blocking (CORB) Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource Fetch API request timeout? How do I post form data with fetch api? Ajax LARAVEL 419 POST error Laravel 5.5 ajax call 419 (unknown status) How to allow CORS in react.js? Angular 2: How to access an HTTP response body? How to post a file from a form with Axios