How to render only data without reloading entire page in node js using ejs templating engine

Viewed 10031

I'm new to Node JS. Below is my code. On AJAX call new data is not being rendered. Is this the right way to render data without loading the entire page? Is there any better way to load only data without using AJAX.

App.js file:

   app.get('/users', function(req, res) {

         var query = req.query.search;

         User.find({'name' : new RegExp(query, 'i')}, function(err, users){
         var data = {list:users};
         console.log("Searching for "+data);

         res.render('admin/users',{data:data});
    });

 });

Ajax call in ejs file:

<script>
function showResult(str) {

    var xmlHttp = null;
    xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", "/admin/users?search="+str, true );
    xmlHttp.send( null );
    return xmlHttp.responseText;
}
</script>

<input type="text" id="search" name="search" placeholder="Search" class="form-control col-md-7 col-xs-12" onkeyup="showResult(this.value)" >
3 Answers

To render EJS partials without reloading the page using ajax, check this thread: Render EJS - Node JS

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)
      }
    })
Related