AJAX call not updating partial page content after clicking backwards/forwards on website

I am trying to generate history states so I can click backwards and forwards on my AJAX-powered pages. It largely works, but on one page my AJAX call doesn’t update page content when I click a button after loading a previous/later page state. Why?

The issue happens with the #filtered_posts div. On my home page, I display posts inside #filtered_posts with a category filter above it. When I click a button on the category filter, it updates the content inside #filtered_posts. If I click back or forward on the homepage without pressing a category filter button, it successfully retrieves the page with the correct state of #filtered_posts. But if I then click on a category filter button, my website URL updates but #filtered_posts doesn’t, and clicking back/forward only changes the URL. How can I fix this?

Also, is there a way for me to only update the state of #filtered_posts when clicking back or forwards on the home page, and update content in the .main div for all other pages?

Here is my simplified code:

    $(document).ready(function () {

        var $mainContent = $(".main");
        var mainContentHTML;
        var value;
        var title;
        var filtered_posts = $("#filtered_posts");

        $(document).on("click", "nav li a", function (e) {
            e.preventDefault();
            value = $(this).attr("href");
            $mainContent.load(value + " .main", function (data) {
                console.log("this function works properly");
            })
        });

        $(document).on("click", "#category-filter li.filter-button", function (e) {
            e.preventDefault();
            value = $(this).find("a").attr("href");
            var category = $(this).data("category");

            $.post(wp_ajax.ajax_url, {
                    action: "filter",
                    category: category
                },
                function (data, status, xhr) {
                    if (status == "success") {
                        filtered_posts.html(data);
                    }
                    if (status == "error") {
                        console.warn(data);
                    }
                });
        });

        //Create history to enable back button functionality
        $(document).ajaxComplete(function (event, jqXHR, settings) {
            mainContentHTML = $(".main").html();
            title = $(document).find("h1.entry-title").text();
            var stateObj = {
                content: mainContentHTML
            };
            window.history.pushState(stateObj, title, value);
        });

        window.addEventListener('popstate', function (event) {
            var state = event.state == null ? mainContentHTML : event.state.content;
            $mainContent.html(state);
        });
    });

17 thoughts on “AJAX call not updating partial page content after clicking backwards/forwards on website”

Leave a Comment