Thursday 20 April 2017

Update part of HTML page using NODE.JS and EJS

I have the following express app which just renders the sample.ejs page. On that page when I press the button the attached script changes the div text to "THIS IS FROM J QUERY. I want the same thing to happen but I want the data to be coming from a database. In my express app if I try to use res.render(); every time I click the button then it reloads the page which I don't want. So is there a way to achieve this without reloading page and only update part of page? I have searched stack overflow and the web but can't get an appropriate answer or maybe I just am unable to understand. I know this is a very basic thing to ask.

APP.js

var express = require('express');
var app = express();
app.use(express.static('public'));
app.use(express.static('./src/views'));
app.set('views', './src/views');
app.set('view engine' , 'ejs');

app.listen(3000 , (err)=>{console.log('Listening')});

app.get('/' , function(req , res) {
    res.render('sample' , {result_from_database: res.body} );   
});

sample.ejs

<!doctype html>
<html lang="en">
<head>
    <title>Sample HTML File</title>
</head>

<body>
    <div id="holder">
        WELCOME
    </div>
    <form>
        <button type="button" id="HButton"> HELLO </button>
    </form>
</body>

<script>
    $(document).ready(function () {
        var form = $("#holder");

        $("#HButton").on("click", function () {
            form.html("THIS IS FROM J QUERY");
        });
    });
</script>

<script src="/lib/jquery/dist/jquery.js"></script>

</html>

Now this is what I want to do

<!doctype html>
<html lang="en">
<head>
    <title>Sample HTML File</title>
</head>

<body>
    <div id="holder">
        <%= result_from_database %>
    </div>
    <form>
        <button type="button" id="HButton"> HELLO </button>
    </form>
</body>

<script>
    $(document).ready(function () {
        var my_div = $("#holder");
        $("#HButton").on("click", function () {

          /* Tell app.js that I clicked a button and then app.js
             query the database and using ejs or something else update the
             my_div inner html with the database result without
             reloading page */
        });
    });
</script>

<script src="/lib/jquery/dist/jquery.js"></script>

</html>

NOTE: I'm not asking how to query the database

-Thanks



via Ahmed.J

No comments:

Post a Comment