Home > Enterprise >  How to create a no refresh page using jquery, express and handlebars?
How to create a no refresh page using jquery, express and handlebars?

Time:09-27

I am learning express JS and my problem is: I want to create two pages using NodeJS, that uses handlebars as template engine, but I want that the first page should be send using res.render('home'), and the second page should be called by jQuery using ajax call to express and get the response as rendered HTML from express server, then load an about page without refreshing. I tried using the method shown in this StackOverflow question but I am not satisfied. please guide me how can i achieve it.

CodePudding user response:

so guys I finally found an answer to my question, I hope you it will help you too. Follow these steps one by one to create a no refresh website using jquery, express and handlebars. Just a tutorial for something that is combination of multiple things.

1. Create a folder name mywebsite

2. run npm init and install the following dependencies

    "express-handlebars": "^5.3.4",
    "handlebars": "^4.7.7",
    "hbs": "^4.1.2"

3. Now create a main.js file with the following code

const express = require('express')
const app = express();
const static_path = __dirname   "/static"
const hbs = require("hbs");

app.set('view engine', 'hbs');
app.set("views", __dirname   "/pages");

app.use(express.static(static_path));

var exhb = require('express-handlebars').create();

app.get("/", (req, res) => {
    res.render('index', { title: "Home Test", pagename: "This is my Home page" });
});

app.get('/getabout', (req, res) => {
    exhb.render("pages/about.hbs", { title: "About US page", body: "Body" }).then((html) => {
        res.send({ data: html });
    }).catch((err) => {
        console.log(err);
    })
});

app.listen(8080, 'localhost', () => {
    console.log("listening at http://localhost:8080")
})

4. Now create a static folder with a file index.js and write the following code

async function callAbout() {
    let data = await fetch('http://localhost:8080/getabout');
    let response = await data.json();
    console.log(response);
    $("html").html(response['data']);
    window.history.pushState(
        'about us',
        'About us',
        '/aboutus');
}

5. Now create a pages folder with two files index.hbs and about.hbs index.hbs will contain the following code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{title}}</title>
</head>
<body>
    <h1>{{pagename}}</h1>
    Lorem ipsum dolor sit amet consectetur adipisicing elit. Sint assumenda aliquam dolor consectetur recusandae possimus illo praesentium atque nihil exercitationem!
    <button onclick="callAbout()">About us</button>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="./index.js"></script>
</body>
</html>

about.hbs will contain the following code

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{title}}</title>
</head>

<body>
<h1>This is my about us page created using NODE</h1>
Lorem ipsum dolor, sit amet consectetur adipisicing elit. Explicabo accusamus autem accusantium suscipit, minima blanditiis ducimus quisquam fugiat, eligendi repellendus provident quasi dolores nesciunt laboriosam commodi illum repellat error eos.
{{body}}
</body>

</html>

6. Now run node.js and click the About Us button and see the magic

Hope this tutorial might help anyone trying to accomplish new things

  • Related