Reload or Refresh a Page after Ajax Success using jQuery

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 this is very simple.

The .reload Method()

The .reload() method, is one of the methods in 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 forseGet 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 it inside our Ajax success function to make it work.

<!DOCTYPE html>
<html>
<head>
    <title>Reload page after Ajax success</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
</head>
<body>
    <p>Refresh page 5 seconds after Ajax success!</p>
    <div id="books" style="margin:5px 0;"></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 />')
                });

                setInterval('location.reload()', 5000);        // Using .reload() method.
            }
        });
    });
</script>
</html>
Try it


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 5 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 you 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: Remember, you should write th refreshPage() function outside $(document).ready() function.

← PreviousNext →


Like this Article? Subscribe now, and get all the latest articles and tips, right in your inbox.

Enter your email id

Delivered by FeedBurner