1

I would like to update my view after an ajax call, rendering compiled ejs from the server.

These two previous questions seem to achieve this but I cannot update my view

Can't Render EJS Template on Client

How to generate content on ejs with jquery after ajax call to express server

So from what I understand I should compile my ejs file (partial) on the server.

fixtures.ejs

<% fixtures.forEach((fixture) => { %>
  <h2><%= fixture.home_team %> vs <%= fixture.away_team %></h2> 
<% }) %>

index.js

app.post('/league_fixtures', async function (req, res) {
  try {
    var league_name = req.body.league_name;
    const fixtures = await leagueFixtures(league_name);
    
    //compile view
    fs.readFile('./views/fixtures.ejs', "utf-8", function(err, template) {
      fixture_template = ejs.compile(template, { client: true });
      var html = fixture_template({fixtures: fixtures});
      console.log(html);
      // This logs out my HTML with fixtures so I am almost there
      // <h2>Club Africain vs Al-Faisaly Amman</h2>
      // <h2>Al Nejmeh vs ASAC Concorde</h2>
    });
    res.json({fixtures: fixtures });
  } catch (err) {
    res.status(500).send({ error: 'Something failed!' })
  }
});

Ajax

$("a.league-name").on("click", function (e) {
  e.preventDefault();
  var league_name = $(this).text().trim();
  
  $.ajax({
    url: '/league_fixtures',
    type: 'POST',
    dataType: "json",
    data: { league_name: league_name },
    success: function(fixtures){
     // How do i get HTML from server into here ?
      $('#panel_' + league_name).html(fixtures);
  },
    error: function(jqXHR, textStatus, err){
      alert('text status '+textStatus+', err '+err)
    }
  })
 });
});

I don't get any errors when I fire the ajax request but I also do not get any data or HTML updated in my div.

What am I doing wrong?

halfer
  • 19,824
  • 17
  • 99
  • 186
Richlewis
  • 15,070
  • 37
  • 122
  • 283

1 Answers1

2

So I finally got a working solution:

index.js

app.post('/league_fixtures', async function (req, res) {
  try {
    const league_name = req.body.league_name;
    const fixtures = await leagueFixtures(league_name);
    const file = await readFile('./views/fixtures.ejs');
    var fixture_template = ejs.compile(file, { client: true });
    const html = fixture_template({fixtures: fixtures});
    res.send({ html: html });
  } catch (err) {
    res.status(500).send({ error: 'Something failed!' })
  }
});

ajax call

$.ajax({
  url: '/league_fixtures',
  type: 'POST',
  dataType: "json",
  cache: true,
  data: { league_name: league_name },
  success: function(fixtures){
    var html = fixtures['html'];
    $('#panel_' + league_name).html(html);
  },
  error: function(jqXHR, textStatus, err){
    alert('text status '+textStatus+', err '+err)
  }
})
halfer
  • 19,824
  • 17
  • 99
  • 186
Richlewis
  • 15,070
  • 37
  • 122
  • 283