Search code examples
javascriptjqueryhtmlajaxpjax

jQuery PJAX plugin not working in HTML website?


I am implementing jQuery PJAX on HTML website but it is not working. I noticed that the area outside the container is getting refreshed.

I have 2 pages: 1. a.html 2. b.html

A.html page code is:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <script src="https://code.jquery.com/jquery-2.2.4.js"
            integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI="
            crossorigin="anonymous"></script>
    <script src="pjax/jquery.pjax.js"></script>
    <script>
        $(function () {
            // pjax
            $(document).pjax('ul a', '#main')
        })
    </script>
</head>
<body>
    Page A
    <div id="main">
        <ul>
            <li><a href="a.html">a</a></li>
            <li><a href="b.html">b</a></li>
        </ul>
    </div>
</body>
</html>

Notice the text outside the container is 'Page A'

B.html page code is:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <script src="https://code.jquery.com/jquery-2.2.4.js"
            integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI="
            crossorigin="anonymous"></script>
    <script src="pjax/jquery.pjax.js"></script>
    <script>
        $(function () {
            // pjax
            $(document).pjax('ul a', '#main')
        })
    </script>
</head>
<body>
    Page B
    <div id="main">
        <ul>
            <li><a href="a.html">a</a></li>
            <li><a href="b.html">b</a></li>
        </ul>
    </div>
</body>
</html>

Notice the text outside the container is 'Page B'

Now, I opened a.html page in browser then cliced on b.html link. And I find that the text becomes Page B. It means the page refreshed, and so jQuery pjax did not worked.

See this below video which illustrates this problem:

enter image description here

What I am doing wrong?


Solution

  • I think pjax probably isn't working because your links are within the pjax container div.

    So the link is telling pjax to use ajax to load all the entire b.html file into <div id='main'>.

    From the pjax documentation:

    pjax works by fetching HTML from your server via ajax and replacing the content of a container element on your page with the loaded HTML. It then updates the current URL in the browser using pushState.

    An example that replaces the some text in #main with the html in b.html and changes the url to b.html.

    File a.html

     <body>
     Page A
     <div>
       <ul>
         <li><a href="b.html">b</a></li>
       </ul>
     </div>
    
     <div id="main">
       some text
     </div>
     </body>
    

    File b.html...

    // b.html
    <p>Replacement text from b.html</p>