Search code examples
jqueryajaxloaddelta

Loading content using AJAX but keep full page when visiting


I have been trying and researching effortlessly for a quite few days now.

Basically, what I'm trying to achieve is AJAX between pages. I know how to load content with AJAX/JQuery from a file into a page but it's a bit different.

Let's say there are 2 pages.

Index.php Info.php

When I click a link from Index.php to Info.php, only the content in a certain DIV (like main content) needs to be replaced.

However, when I visit Index.php, I get the full page with headers and all that. (obviously) But, if I visit Info.php, I also want to get that full page with headers and everything (just with the difference in the content DIV).

I see this on website quite a lot but just can't seem to find or figure out how it works.

It could also basically maybe be something like just replacing everything that's different between the two pages? (Like delta loading, as it seems to be called)

The main thing for all of this is to keep a music player playing fluently between page loads.

Can anyone explain how this would work or push me in the right direction?

Many thanks! :)


Solution

  • You can do something like this

    Assume that your all content of page in #container div

    your navigation links looks like

    <a href="index.php" class="ajax_link">Home<a>
    <a href="infor.php" class="ajax_link">Information<a>
    

    in your javascript code with jquery

    function ajaxPageLoader(request_url) {
        console.log("Content loading from : "+request_url);
        $("#container").load(request_url+" #container", function() {
            window.history.pushState({}, "", request_url); // update current url in browser.
            console.log("Content loaded");
        });
    }
    
    function changeState(state) {
        if(state !== null) { // initial page
            ajaxPageLoader(state.url);
        }
    }
    

    This is delegated event handler using on() method

    $(document).ready(function(){
        $(document).on('click','.ajax_link',function(){
            ajaxPageLoader($(this).attr('href'));
            return false;
        });
    });
    // back button event
    $(window).on("popstate", function(e) {
        changeState(e.originalEvent.state);
        return false;
    });