Maximizing the potential of PJAX with Express and EJS: A guide

Hey there, question coming from a newbie in the world of coding. I've been struggling to make pjax work for quite some time now without any success. The closest I've come is seeing some activity in the terminal, but when I click on the link, it just takes me to a different page instead of loading its content within a specific div.

I even tried referencing Chris Wanstrath's pjax source code but still no luck.

//Here's the snippet from the schedule.js file
router.get('/', function(req, res) {
  res.render('schedule', { title: 'Schedule' });
});

//This is the jQuery part of the script
$(document).pjax('a[data-pjax]', '#pjax-container');
<li><a data-pjax="#pjax-container" href="/schedule">Schedule</a></li>
 
 <div id="pjax-container"> 
 </div>

Answer №1

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>

<% } %>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The .get function is functioning properly during development, but encountering issues in the production environment

Here is the scenario: while running my server on node.js locally, the client code successfully retrieves data from the server. However, upon pushing the code to the live server, the client receives a /getSettings 500 (Internal Server Error). The main index ...

NodeJS constantly communicating with Rest API

Entering the world of Node.js is a new journey for me. I have a service with two endpoints available. The first endpoint is a post method that takes in a payload, processes it asynchronously, and immediately sends an acknowledgment to the caller. The secon ...

Struggling with ajax: Converting a JavaScript variable to a PHP variable

I'm trying to convert a JavaScript variable into a PHP variable in order to use it in an SQL query, but for some reason it's not working as expected. Here is the HTML code: <select id = "dep_ID" name = "dep_ID" onchange="myFunction()"> A ...

Prevent clicking on form until setInterval has been cleared using React useEffect

Here is a link to a sandbox replicating the behavior: sandbox demo I have integrated a hook in a React component to act as a countdown for answering a question. React.useEffect(() => { const timer = setInterval(() => { setTimeLeft((n ...

What is preventing access to the global scope in this particular situation?

Recently, I encountered a problem where I was able to pass through the issue but couldn't fully grasp the concept behind it. If you run the code snippet provided, you'll see what's happening. Can someone clarify this for me? function fu ...

Tips for Determining the Lifecycle of a REST API Response

I am in the process of developing REST APIs using NodeJS and the Express framework. The User API is one of them. However, I am uncertain about how to properly handle responses for each scenario within the API. The sequence of sending response HTTP status c ...

Ways to eliminate the initial digit of a decimal number if it is less than 1

I need assistance with modifying float values by removing the first number if it's lower than 1 In the "OPS" table section, I am calculating the sum of OBP and SLG obtained from a database. https://i.sstatic.net/cYwwW.jpg See the code snippet below ...

Is there a way to retrieve a JSON result from an API call using jQuery (or plain JavaScript) without relying on Ajax?

As someone new to JS and jQuery, I am working on building a key-value map from an API call that returns an array of key-value pairs. [{"key":"191","value":244}, ... , {"key":"920","value":130}] I have created the following ajax code in my attempt to achi ...

Creating a query model that is tailored to the specific values found within one of its columns

I need assistance with a sequelize operation involving my staff model. Within the staff table, there is a column named locations that stores the IDs of various locations where each staff member is available. My goal is to create a query that uses a speci ...

Validating dates using JQuery within a specific range of dates

Users can input a date within a specified range in an input field. To enable this feature, I created a new method using the jQuery validator object: $.validator.addMethod("dateRange", function(value, element, from, to){ try { var date = new D ...

Verifying user identity on Android app using PassportJS

Utilizing passportjs for user authentication on my web app has worked effectively. Now, in the process of developing an Android client for the same project, I encountered an issue. Upon logging in with the local strategy on Android, successful authenticati ...

Generating swagger documentation for TypeScript-based Express applications

I have successfully set up the swagger URL following a helpful guide on configuring Swagger using Express API with autogenerated OpenAPI documentation through Swagger. Currently, I am utilizing TypeScript which outputs .js files in the dist folder without ...

Utilizing Rails to incorporate a comment box through jquery on individual posts within a index page showcasing all listed posts

As I display a list of posts on my index file, I want each post to have its own comments section. To achieve this, I have added a "Show Comments" button for each post. However, when I click the button, jQuery triggers all comment boxes on the page instead ...

What is the best way to handle sequential $http calls in AngularJS? Specifically, I want to make the second $http call dependent on the response of the first

When making two $http calls, the second call should only be executed based on the response from the first call if there is an error present. ...

Retrieve Javascript files from the local static directory

Currently, I am developing a small project with Nuxt JS and I am facing a challenge in calling some Javascript files from my static directory. When it comes to CSS files, I have been able to do it successfully using the following code: css: [ './stat ...

Connecting Ionic/Angular directives to scrollbars

I'm having an issue with my scrolling div: <div class="list"> <div class="item" ng-repeat="post in posts"> <img src="post.img" is-visible/> </div> </div> and I've implemented this directive: angular.elemen ...

Text field suddenly loses focus upon entering a single character

In my current code, I have functions that determine whether to display a TextField or a Select component based on a JSON value being Text or Select. However, I am facing an issue where I can only enter one letter into the TextField before losing focus. Sub ...

Ways to update the component's state externally

I'm new to Next.js (and React) and I'm attempting to update the state of a component from outside the component. Essentially, I am conditionally rendering HTML in the component and have a button inside the component that triggers a function to se ...

Click outside of this popup to dismiss it

I have been struggling to figure out how to make this popup close when clicking outside of it. Currently, it only closes when clicked directly on it. Your assistance in this matter is greatly appreciated. Here is the HTML code: <h2>Popup</h2> ...

Utilizing slug URLs effectively in Next.js

In my current project with Next.js, I am working on implementing "dynamic routes". The goal is to update the URL structure such that upon clicking, the URL should look like "myurl.com/article/55". To achieve this, I have utilized the following "link tag": ...