How do I update EJS template + AJAX? How do I update EJS template + AJAX? mongoose mongoose

How do I update EJS template + AJAX?


When you call res.render(), you are telling Express to look up a template (in this case, EJS), and "compile" it using some custom data. It then sends the compiled HTML back in the response to the request. In other words, your API does not serve JSON; it serves server-rendered HTML.

On the client side, you can just insert this HTML where you want it in the DOM:

$.get('/jobs', function(html) {  $('#jobs-container').html(html);});

An alternative method would be to serve only JSON from the API, and then render all the HTML on the side of your browser. In this model, you can throw out your server-side EJS template:

// router.jsrouter.get('/jobs', function(req, res) {  Job.find(function(err, jobs) {    res.send(jobs);  });});

On the client:

// custom.js$.get('/jobs', function(jobs) {  var $jobs = $('<div class="col-md-4"></div>');  jobs.forEach(function(job) {    $jobs.append(`<h1>${job.title}</h1>`);  });  $('#jobs-container').html($jobs);});

There are many considerations to take when choosing to render your HTML on the client vs. server. This article by Karl Seguin is a good starting place on the subject.


I'm not sure what you're trying to achieve, but res.json is doing what you probably want. The documentation have it all covered.

router.get('/jobs', function(req, res) {    Job.find({}, function(err, jobs) {        if (req.xhr) { // request was AJAX (XHR)            res.json({error: err, jobs: jobs});        } else { // render html template instead            res.render('main/job', {                jobs: jobs,                message: req.flash('message')            });                    }     });});