How do I get PJAX to work with Express and EJS?

Okay, a question from noob land. But I've been trying to get pjax to work for a while and nothing seems to work. The best I got was the process confirmation in the terminal, but when I click on the link it takes me to a whole other page instead of displaying its content in the specified div.

And I've also included a link to the Chris Wanstrath pjax source code. Nothing seems to work.

//The schedule.js file 
router.get('/', function(req, res) {
  res.render('schedule', { title: 'Schedule' });
});

//The jQuery end of the line
$(document).pjax('a[data-pjax]', '#pjax-container');
      

 <li><a data-pjax="#pjax-container" href="/schedule">Schedule</a></li>
 
 <div id="pjax-container"> 
 </div>
      

Run codeHide result


+3


source to share


1 answer


I found that pjax can be configured correctly and still reload the page if you submit a tag <html>

with a payload and then trigger a reload - perhaps when you make a request, that's why your page is loading?

Also, the default timeout for a failed server request is set to around 600ms, so in the code below I have increased the default to 5000ms.

You will need to distinguish back-end whether the request is part of a document or a complete document using the http header "X-PJAX"

pjax adds to the header.

Here is my solution for this using nodejs / express 5 / pjax

create a helper file named pjax-helper.js

with the following content

'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 application, you may need the file

var pjax = require('./include/pjax-helper');

and at one time the express is loaded ...



app.use(pjax());

You will now have a variable available in both your application and your view layer


In my case, using the EJS templating engine, I did something like 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>

<% } %>

      

+3


source







All Articles