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.

jQuery .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() 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>

    <!--fill DIV with data after a successful Ajax call-->
    <div id='books'></div>
</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 />')
                });

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

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

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

← PreviousNext →