Reload or Refresh a Page after Ajax Success using jQuery

← PrevNext →

You can use the location.reload() method to reload or refresh an entire web page or just the content inside an element. The .reload() method can be triggered either explicitly (with a button click) or automatically. You can also use the .reload() method inside an Ajax success callback function and I'll show you how simple it is.

The .reload Method()

The .reload() method, is one of the many methods (like the .replace() method) of the location object. The location object contains information about a URL (see the URL of this page in the browser’s address bar).

The .reload() method takes a Boolean value forceGet as parameter. Therefore, it can be either …

location.reload(true); // the value "true" ensures that the current page is fully loaded ignoring the "cache".

OR

location.reload(false);

Now, lets add the method inside our Ajax "success" function and see how it works.

<body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>

    <p>Refresh page 7 seconds after Ajax success.</p>
    <div id='books'></div>         <!--fill DIV with data after a successful Ajax call-->
</body>
<script>
    $(document).ready(function () {
        $('#books').empty();

        $.ajax({
            type: 'GET',
            url: '../../library/library.xml',
            dataType: 'xml',
            success: function (xml) {

                $(xml).find('List').each(function () {
                    $('#books').append(
                        $(this).find('BookName').text() + '<br />')
                });

                setInterval('location.reload()', 7000);        // Using .reload() method.
            }
        });
    });
</script>
</html>
You should try this

👉 Do you know you can auto refresh a page every few seconds using plain old JavaScript? Check this out.
Refresh page every 10 seconds using JavaScript

The location.reload() method, will reload (or refresh) an entire web page after the Ajax has performed its operation, that is, extracted data from an xml file. Therefore, I have added location.reload() inside the "success" callback function.

In addition, I have used the setInterval() method to set a delay of 7 seconds to do the reload process. This is optional however. You can call the reload without any delay.

If you are using setInterval() method in your example, you can also do this …

$(document).ready(function () {
    $.ajax({
        type: 'GET',
        url: '../../library/library.xml',
        dataType: 'xml',
        success: function (xml) {
            setInterval('refreshPage()', 5000);
        }
    });
});

function refreshPage() {
    location.reload(true);
}

👉 You may also like : How to refresh the contents of a DIV element automatically every few seconds using jQuery
Refresh DIV every few seconds using jQuery

Note: You should write the "refreshPage()" function outside "$(document).ready()" function.

← PreviousNext →