PJAX jQuery Plugin

date_range  25 January 2014

jQuery
ASP.Net
Tutorial

My previous article on this topic is a bit outdated now.  I’ve now created a plugin to achieve this functionality and extended its capabilities.

Code

The plugin can be pulled from Github:

Options

| Name | Type | Default | Description | | locationAttribute | string | href | The attribute of the element that when clicked, pjax will look for to get the link to follow to get the page to load from. | | pjaxLinkSelector | string | a[data-pjax="true"] | A selector for pjax to use to create links from. | | analytics | Google Analytics | null | A Google Analytics object to track pageviews of pjax loaded pages. | | preLoad | function(){} | null | A function that will be executed when a link is clicked, but before an ajax request is made to pull the page. | | postLoad | function(){} | null | A function that will be executed after page content has been replaced. | | onErrorLoading | function(){} | null | A function that will be executed if the page content could not be loaded. |

Usage

Pjax works by selecting a container and then giving it a function telling it what to do with the data retrieved from a followed link.

	$('body').pjax({ onLoad: function(data, status, xhr){ $('#content').html(data); });

That is the minimum required client side to get a link like this \u0026lt;a href=”/home/other” data-pjax=”true”\u0026gt;Link\u0026lt;/a\u0026gt; to pull back the page at /home/other and insert that data into the #content container.

Server-side, a couple other things need to be done so that the outer content/layout of the page isn’t pulled back with the page content.

We need to check whether the request for the page required it’s layout or now.  Pjax sends back a customer header X-PJAX so that the server can distinguish this.

In the _ViewStart.cshtml we check for it and return a different layout file.

	@{ 
		Layout = Request.Headers["X-PJAX"] != null ? "~/Views/Shared/_PjaxLayout.cshtml" : "~/Views/Shared/_Layout.cshtml"; 
	}

To get the title to be set as well when a Pjax request is made add this into the pjax layout file.

	Response.AddHeader("X-PJAX-Title", @Viewbag.Title");

Then you should be all set.  There should no reason this plugin would not work with any other server side framework but I have only used it with ASP.Net MVC.  I shall upload a demo in due course.

comments powered by Disqus

chevron_left Archive