After some experimentation, I discovered that even if pjax is set up correctly, the page can still reload if an <html>
tag is sent with the payload. This may be causing your page to reload whenever a request is made.
Furthermore, the default timeout for a failed server request is approximately 600ms, but in the code snippet below, I have increased it to 5000ms.
To distinguish between whether the request is for part of the document or the entire document on the server side, you need to utilize the http header "X-PJAX"
, which pjax appends to the header.
Below is my solution using nodejs / express 5 / pjax:
Create a helper file named pjax-helper.js
with the following contents:
'use strict';
module.exports = function() {
return function pjax( req, res, next ) {
if( req.header( 'X-PJAX' ) ) {
req.pjax = true;
res.locals.pjax = true;
} else {
req.pjax = false;
res.locals.pjax = false;
}
next();
};
};
In your app, require the file like this:
var pjax = require('./include/pjax-helper');
Then, once express is loaded...
app.use(pjax());
Now, you will have access to the variable in both your app and your view layer.
In my scenario using the EJS template engine, I implemented something similar to this:
//schedule.ejs:
<%- include('includes/header') %>
<h1><%= title %></h1>
<%- include('includes/footer') %>
--
//includes/header.ejs
<% if(locals.pjax==false) { %>
<!DOCTYPE html>
<html lang="en">
<head> ... </head>
<body>
<%- include('menu') %>
<div id="pjax-container">
<% } %>
--
//includes/footer.ejs
<% if(locals.pjax==false) { %>
</div><!--/#pjax-ccontainer-->
<script src="/js/pjax.js"></script>
<script>
$(document).pjax('a.pjax', '#pjax-container', {timeout: 5000});
$(document).on('pjax:send', function() { $('#loading').show(); });
$(document).on('pjax:complete', function() { $('#loading').fadeOut(); });
</script>
</body>
</html>
<% } %>