Skip to content


Subversion checkout URL

You can clone with
Download ZIP
Browse files

Merge pull request #226 from defunkt/new-readme

Rewrite README
  • Loading branch information...
commit 29208e6771887462185340c7897b9306dd042fd3 2 parents 4bb8554 + bd9b103
@josh josh authored
Showing with 178 additions and 187 deletions.
  1. +178 −187
@@ -1,4 +1,5 @@
-## pushState + ajax = pjax
+# pjax
/ \
@@ -20,283 +21,273 @@
jgs |___\_.\_
+## pjax = pushState + ajax
-## what is it?
-pjax loads HTML from your server into the current page
-without a full reload. It's ajax with real permalinks,
-page titles, and a working back button that fully degrades.
+pjax is a jQuery plugin that uses ajax and pushState to deliver a fast browsing experience with real permalinks, page titles, and a working back button.
-pjax enhances the browsing experience - nothing more.
+pjax works by grabbing html from your server via ajax and replacing the content of a container on your page with the ajax'd html. It then updates the browser's current url using pushState without reloading your page's layout or any resources (js, css), giving the appearance of a fast, full page load. But really it's just ajax and pushState.
-You can find a demo on <>
+For [browsers that don't support pushState][compat] pjax fully degrades.
+## Overview
-## three ways to pjax on the client side:
+pjax is not fully automatic. You'll need to setup and designate a containing element on your page that will be replaced when you navigate your site.
-One. Functionally obtrusive, loading the href with ajax into data-pjax:
-<a href='/explore' data-pjax='#main'>Explore</a>
+Consider the following page.
+``` html
+<!DOCTYPE html>
+ <!-- styles, scripts, etc -->
+ <h1>My Site</h1>
+ <div class="container" id="pjax-container">
+ Go to <a href="/page/2">next page</a>.
+ </div>
+We want pjax to grab the url `/page/2` then replace `#pjax-container` with whatever it gets back. No styles or scripts will be reloaded and even the h1 can stay the same - we just want to change the `#pjax-container` element.
-Two. Slightly obtrusive, passing a container and binding an error handler:
+We do this by telling pjax to listen on `a` tags and use `#pjax-container` as the target container:
-<a href='/explore' class='js-pjax'>Explore</a>
+``` javascript
+$(document).pjax('a', '#pjax-container')
-$('#main').pjax('.js-pjax').on('pjax:error', function(e, xhr, err) {
- $('.error').text('Something went wrong: ' + err)
+Now when someone in a pjax-compatible browser clicks "next page" the content of `#pjax-container` will be replaced with the body of `/pjax/2`.
+Magic! Almost. You still need to configure you server to look for pjax requests then send back pjax-specific content.
-Three. Unobtrusive, showing a 'loading' spinner:
+The pjax ajax request sends an `X-PJAX` header so in this example (and in most cases) we return a page without a layout to any requests with that header.
-<div id='main'>
- <div class='loader' style='display:none'><img src='spin.gif'></div>
- <div class='tabs'>
- <a href='/explore'>Explore</a>
- <a href='/help'>Help</a>
- </div>
+Here's what it might look like in Rails:
-$('#main').pjax('a').on('pjax:send', function(){
- $(this).showLoader()
+``` ruby
+def index
+ if request.headers['X-PJAX']
+ render :layout => false
+ end
+If you'd like a more automatic solution than pjax for Rails check out [Turbolinks](
-## $(container).pjax( link, options )
+## Installation
-The `$(container).pjax(selector)` uses the jquery context as the
-default container pjax. The link selector is used to match against
-delegated click events to start pjaxing.
+### bower
-The options are the same as jQuery's `$.ajax` options with the
-following additions:
-* `container` - The String selector of the container to load the
- reponse body. Must be a String.
-* `target` - The Element that was clicked to start the pjax call.
-* `push` - Whether to pushState the URL. Default: true (of course)
-* `replace` - Whether to replaceState the URL. Default: false
-* `timeout` - pjax sets this low, <1s. Set this higher if using a
- custom error handler. It's ms, so something like
- `timeout: 2000`
-* `fragment` - A String selector that specifies a sub-element to
- be pulled out of the response HTML and inserted
- into the `container`. Useful if the server always returns
- full HTML pages.
+Via [bower](
+$ bower install jquery-pjax
-## $.pjax( options )
+Or add `jquery-pjax` to your apps `component.json`.
-You can also just call `$.pjax` directly. It acts much like `$.ajax`, even
-returning the same thing and accepting the same options.
+``` json
+ "dependencies": {
+ "jquery-pjax": "latest"
+ }
-The pjax-specific keys listed in the `$(link).pjax()` section work here
-as well.
+### standalone
-This pjax call:
+pjax can be downloaded directly into your app's public directory - just be sure you've loaded jQuery first.
- url: '/authors',
- container: '#main'
-Roughly translates into this ajax call:
- url: '/authors',
- dataType: 'html',
- beforeSend: function(xhr){
- xhr.setRequestHeader('X-PJAX', 'true')
- },
- success: function(data){
- $('#main').html(data)
- history.pushState(null, $(data).filter('title').text(), '/authors')
- })
+curl -O
+**WARNING** Do not hotlink the raw script url. GitHub is not a CDN.
-## pjax on the server side
+## Dependencies
-You'll want to give pjax requests a 'chrome-less' version of your page.
-That is, the page without any layout.
+Requires jQuery 1.7.x or higher.
-As you can see in the "ajax call" example above, pjax sets a custom 'X-PJAX'
-header to 'true' when it makes an ajax request to make detecting it easy.
+## Compatibility
-In Rails, check for `request.headers['X-PJAX']`:
+pjax only works with [browsers that support the `history.pushState` API][compat]. When the API isn't supported pjax goes into fallback mode: `$.fn.pjax` calls will be a no-op and `$.pjax` will hard load the given url. This mode targets the browser requirements of the jQuery version being used.
-def my_page
- if request.headers['X-PJAX']
- render :layout => false
- end
+For debugging purposes, you can intentionally disable pjax even if the browser supports `pushState`. Just call `$.pjax.disable()`. To see if pjax is actually supports `pushState`, check `$.support.pjax`.
-Or as a before filter in application controller:
+## Usage
-layout :set_layout
+### `$.fn.pjax`
- def set_layout
- if request.headers['X-PJAX']
- false
- else
- "application"
- end
- end
+Let's talk more about the most basic way to get started:
+``` javascript
+$(document).pjax('a', '#pjax-container')
-Rails: <>
+This will enable pjax on all links and designate the container as `#pjax-container`.
-Django: <>
+If you are migrating an existing site you probably don't want to enable pjax everywhere just yet. Instead of using a global selector like `a` try annotating pjaxable links with `data-pjax`, then use `'a[data-pjax]'` as your selector.
-Asp.Net MVC3: <>
+Or try this selector thats matches any `<a data-pjax href=>` links inside a `<div data-pjax>` container.
-FuelPHP: <>
+``` javascript
+$(document).pjax('[data-pjax] a, a[data-pjax]', '#pjax-container')
-Grails: <>
+When invoking `$.fn.pjax` there are a few different argument styles you can use:
-Express: <>
+1. `$(document).pjax(delegation selector, options object)`
+2. `$(document).pjax(delegation selector, container selector, options object)`
+In other words:
-## page titles
+1. The first argument must always be a `String` selector used for delegation.
+2. The second argument can either be a `String` container selector or an options object.
+3. If there are three arguments the second must be the `String` container selector and the third must be the options object.
-Your HTML should also include a `<title>` tag if you want page titles to work.
+### `$`
-When using a page fragment, pjax will check the fragment DOM element
-for a `title` or `data-title` attribute and use any value it finds.
+This is a lower level function used by `$.fn.pjax` itself. It allows you to get a little more control over the pjax event handling.
+This example uses the current click context to set an ancestor as the container:
-## events
+``` javascript
+if ($.support.pjax) {
+ $(document).on('click', 'a[data-pjax]', function(event) {
+ var container = $(this).closest('[data-pjax-container]')
+ $, {container: container})
+ })
-pjax will fire two events on the container you've asked it to load your
-reponse body into:
+**NOTE** Use the explicit `$.support.pjax` guard. We aren't using `$.fn.pjax` so we should avoid binding this event handler unless the browser is actually going to use pjax.
-* `pjax:start` - Fired when a pjax ajax request begins.
-* `pjax:end` - Fired when a pjax ajax request ends.
+### `$.pjax.submit`
-This allows you to, say, display a loading indicator upon pjaxing:
+Submits a form via pjax. This function is experimental but GitHub uses it on [Gist][gist] so give it a shot!
- .on('pjax:start', function() { $('#loading').show() })
- .on('pjax:end', function() { $('#loading').hide() })
+``` javascript
+$(document).on('submit', 'form[data-pjax]', function(event) {
+ $.pjax.submit(event, '#pjax-container')
-Because these events bubble, you can also set them on the document:
+### `$.pjax`
- .on('pjax:start', function() { $('#loading').show() })
- .on('pjax:end', function() { $('#loading').hide() })
+Manual pjax invocation. Used mainly when you want to start a pjax request in a handler that didn't originate from a click. If you can get access to a click `event`, consider `$` instead.
-In addition, custom events are added to complement `$.ajax`'s
+``` javascript
+function applyFilters() {
+ var url = urlForFilters()
+ $.pjax({url: url, container: '#pjax-container'})
-* `pjax:beforeSend` - Fired before the pjax request begins. Returning
- false will abort the request.
-* `pjax:complete` - Fired after the pjax request finishes.
-* `pjax:success` - Fired after the pjax request succeeds.
-* `pjax:error` - Fired after the pjax request fails. Returning
- false will prevent the the fallback redirect.
-* `pjax:timeout` - Fired if after timeout is reached. Returning
- false will disable the fallback and will wait
- indefinitely until the response returns.
+### Events
-**CAUTION** Callback handlers passed to `$.pjax` **cannot** be persisted
-across full page reloads. Its recommended you use custom events instead.
+pjax fires a number of events regardless of how its invoked.
-## browser support
+All events are fired from the container, not the link was clicked.
-pjax only works with browsers that support the history.pushState API.
+#### start and end
-For a table of supported browsers see: <>
+* `pjax:start` - Fired when pjaxing begins
+* `pjax:end` - Fired when pjaxing ends.
-To check if pjax is supported, use the `$.support.pjax` boolean.
+This pair events fire anytime a pjax request starts and finishes. This includes pjaxing on `popstate` and when pages are loaded from cache instead of making a request.
-When pjax is not supported, `$('a').pjax()` calls will do nothing (aka links
-work normally) and `$.pjax({url:url})` calls will redirect to the given URL.
+#### ajax related
+* `pjax:beforeSend` - Fired before the pjax request begins. Returning false will abort the request.
+* `pjax:send` - Fired after the pjax request begins.
+* `pjax:complete` - Fired after the pjax request finishes.
+* `pjax:success` - Fired after the pjax request succeeds.
+* `pjax:error` - Fired after the pjax request fails. Returning false will prevent the the fallback redirect.
+* `pjax:timeout` - Fired if after timeout is reached. Returning false will disable the fallback and will wait indefinitely until the response returns.
-## install it
+`send` and `complete` are a good pair of events to use if you are implementing a loading indicator. They'll only be triggered if an actual request is made, not if it's loaded from cache.
-$ cd path/to/js
-$ wget
+``` javascript
+$(document).on('pjax:send', function() {
+ $('#loading').show()
+$(document).on('pjax:complete', function() {
+ $('#loading').hide()
-Then, in your HTML:
+Another protip: disable the fallback timeout behavior if a spinner is being shown.
-<script src="path/to/js/jquery.pjax.js"></script>
+``` javascript
+$(document).on('pjax:timeout', function(event) {
+ // Prevent default timeout redirection behavior
+ event.preventDefault()
-Replace `path/to/js` with the path to your JavaScript directory,
-e.g. `public/javascripts`.
+### Server side
+Server configuration will vary between languages and frameworks. The following example shows how you might configure Rails.
-## upgrade it
+``` ruby
+def index
+ if request.headers['X-PJAX']
+ render :layout => false
+ end
-pjax 1.0 includes some breaking changes.
+An `X-PJAX` request header is set to differentiate a pjax request from normal XHR requests. In this case, if the request is pjax, we skip the layout html and just render the inner contents of the container.
-The main API was changed.
+Check if your favorite server framework supports pjax here:
-Old: `$(link).pjax( container, options )`
+### Legacy API
-New: `$(container).pjax( link, options )`
+Pre 1.0 versions used an older style syntax that was analogous to the now deprecated `$` api. The current api is based off `$.fn.on`.
-Instead of this:
+``` javascript
- $('a[data-pjax]').pjax()
+Expanded to
-Do this:
+``` javascript
+$('a[data-pjax]').live('click', function(event) {
+ $, '#pjax-container')
- $(document).pjax('a[data-pjax]')
+The new api
-These options were removed:
+``` javascript
+$(document).pjax('a[data-pjax]', '#pjax-container')
-* `clickedElement` - Use `target` instead
-* `beforeSend` - Bind to `pjax:beforeSend` instead
-* `complete` - Bind to `pjax:complete` instead
-* `success` - Bind to `pjax:success` instead
-* `error` - Bind to `pjax:error` instead
+Which is roughly the same as
-These events were removed:
+``` javascript
+$(document).on('click', 'a[data-pjax]', function(event) {
+ $, '#pjax-container')
+**NOTE** The new api gives you control over the delegated element container. `$` always bound to `document`. This is what you still want to do most of the time.
-* `pjax` - Use `pjax:start`
-* `start.pjax` - Use `pjax:start`
-* `end.pjax` - Use `pjax:end`
+## Contributing
+$ git clone
+$ cd jquery-pjax/
-## minimize it
+To run the test suite locally, start up the Sinatra test application.
-curl \
- -d output_info=compiled_code \
- -d compilation_level=SIMPLE_OPTIMIZATIONS \
- -d code_url= \
+$ ruby test/app.rb
+== Sinatra/1.3.2 has taken the stage on 4567 for development with backup from WEBrick
+$ open http://localhost:4567/
Please sign in to comment.
Something went wrong with that request. Please try again.