Load HTML page dynamically into div with jQuery

There’s a jQuery plugin out there called pjax it states: “It’s ajax with real permalinks, page titles, and a working back button that fully degrades.”

The plugin uses HTML5 pushState and AJAX to dynamically change pages without a full load. If pushState isn’t supported, PJAX performs a full page load, ensuring backwards compatibility.

What pjax does is that it listens on specified page elements such as <a>. Then when the <a href=""></a> element is invoked, the target page is fetched with either the X-PJAX header, or a specified fragment.

Example:

<script type="text/javascript">
  $(document).pjax('a', '#pjax-container');
</script>

Putting this code in the page header will listen on all links in the document and set the element that you are both fetching from the new page and replacing on the current page.

(meaning you want to replace #pjax-container on the current page with #pjax-container from the remote page)

When <a> is invoked, it will fetch the link with the request header X-PJAX and will look for the contents of #pjax-container in the result. If the result is #pjax-container, the container on the current page will be replaced with the new result.

<!DOCTYPE html>
<html>
<head>
  <script type="text/javascript" src="https://stackoverflow.com/questions/14735762/jquery.min.js"></script>
  <script type="text/javascript" src="jquery.pjax.js"></script> 
  <script type="text/javascript">
    $(document).pjax('a', '#pjax-container');
  </script> 
</head>
<body>
  <h1>My Site</h1>
  <div class="container" id="pjax-container">
    Go to <a href="http://stackoverflow.com/page2">next page</a>.
  </div>
</body>
</html>

If #pjax-container is not the first element found in the response, PJAX will not recognize the content and perform a full page load on the requested link. To fix this, the server backend code would need to be set to only send #pjax-container.

Example server side code of page2:

//if header X-PJAX == true in request headers, send
<div class="container" id="pjax-container">
  Go to <a href="https://stackoverflow.com/page1">next page</a>.
</div>
//else send full page

If you can’t change server-side code, then the fragment option is an alternative.

$(document).pjax('a', '#pjax-container', { 
  fragment: '#pjax-container' 
});

Note that fragment is an older pjax option and appears to fetch the child element of requested element.

Leave a Comment