Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use PJAX? (PJAX With PHP?)

I was trying to get PJAX working with my PHP site, this is the code I am using for it:

<script src="js/jquery.js"></script> 
<script src="js/jquery.pjax.js"></script>
    <script type="text/javascript">
        $(function(){
            // pjax
            $('ul a').pjax('section')
        })
    </script>

I am just using the code they used on the PJAX demo page, but replacing the container they used (#main) with the one for my site, which was the section tag. There are no errors on the console or on the page, but it doesn't work either! Before I was using

$(function() { $('ul a').pjax('section') }); and

$('document').ready(function(){
   $('ul a').pjax('section')
});

But when I don't use either of those and just use $('ul a').pjax('section') I see this error in the console:

Uncaught no pjax container for section in jquery.pjax.js (line: 353)

Could I get some help with this? Thanks

like image 983
user1302430 Avatar asked Apr 04 '12 01:04

user1302430


1 Answers

By default, pjax expects new pages to be delivered without the chrome - a HTML snippet that will be used as the innerHTML of the container.

In your example the container would be the first <section> tag I suppose. I don't know if pjax guarantees that it will use the first element that matches a selector - it may just replace every matching element. Probably it would be better to use an ID selector, such as #main.

Anyway, it sounds like you weren't delivering HTML snippets, but just the whole page. This almost defeats the purpose of pjax, but it can be supported by specifying a fragment in the downloaded content. Almost always this will be a selector that matches the container which will be replaced.

So, assuming you use a container with @id=main you could call pjax with

$(function() { $("ul a").pjax("#main", { fragment: "#main" }); });

Make sure that pjax is called after the document loads, otherwise the container lookup will fail.

By the way, an easier way to switch to pushState assisted navigation is with my HTMLDecor project. It requires you to change your perspective on generating HTML pages, but once you've done that you just need to add the HTMLDecor.js script to your pages and pushState is used automatically when appropriate - no config needed.

like image 177
Sean Hogan Avatar answered Sep 27 '22 17:09

Sean Hogan