Refresh section of a page using EJS and Express

Issue

I have a checkbox that when pressed call a function that does a GET request. Based on the selection I want to display extra checkboxes on the same page. At the moment this is the code I have so far:

Client side

function selectedHouse(house)
{
   if(house.checked){
      $.get('/', {data: house.value});
   }
}

Server side

var routing = function (nav, houses) {
    router.route('/')
        .get(function (req, res) {
            var rooms = [];
            rooms = getRooms(req.query.data);
            console.log(rooms);

            res.render('index', {
                title: 'Independent cleaner',
                nav: nav,
                houses: houses,
                roomsForHouse: rooms
            });
        });
    return router;
};

The first time the page loads, it loads with the correct title, nav and houses. When the function is executed on client side, I get back the related rooms for the house and I’m trying to populate the roomsForHouse variable which I’m displaying on the view.

The problem is that the view doesn’t render the roomsForHouse variable. So the GET request is called once the page loads and a second time when the function executes. Can this be achieved?

Solution

It’s a bit more complex. You’ll need to use ajax for this. EJS is server side templates (as you are using them) so you’ll want to use jQuery to make the call and update your already rendered page.

Server
Your server will need a route that delivers JSON data. Right now you are rendering the entire page. So:

app.get('/rooms/:id',  function (req, res) {

  // Get the house info from database using the id as req.params.id
  ...

  // Return the data
  res.json({
    rooms: 2
    ...
  });
});

Client

Using jQuery make a call to your json route once the user selects the house.

function selectedHouse(house)
{
   if(house.checked){
      // Pass some identifier to use for your database
      $.ajax({
        type: 'GET',
        url: '/rooms/' + house.id,
        success: function(data) {
          // Update the element - easiet is to use EJS to make sure each house has an id/class with the id in it
          // Given an ID of 2 this says find the div with class house_2 and updates its div with class room to the number of rooms
          $('.house_' + house.id + ' .rooms').text(data.rooms);  
      });
   }
}

This is more of pseudo code then anything but should put you on the right track.

Answered By – cyberwombat

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published