5

I want to implement a search feature on my website so what i do is make a jquery ajax call with the text to the express server which searches mongodb and gives an object array of the users that match. Now i receive this object succesfully but since there are no partials on ejs how can i refresh just the results list generating the html for each user?

anges244
  • 697
  • 2
  • 12
  • 25

1 Answers1

9

The node EJS packages comes with a client-side javascript library located in ./node_modules/ejs/ejs.js or ./node_modules/ejs/ejs.min.js. After you include this on your page, you'll want to load the template, then generate the HTML from the template. Detecting an undefined object property Javascript Sample (loading the template on page load would be a bit more ideal):

function getData() {
    // Grab the template
    $.get('/results.ejs', function (template) {
        // Compile the EJS template.
        var func = ejs.compile(template);

        // Grab the data
        $.get('/data', function (data) {
           // Generate the html from the given data.
           var html = func(data);
           $('#divResults').html(html);
        });
    });
}

EJS:

<table>
    <tr>
        <th>ID</th>
        <th>Name</th>
    </tr>   
    <% data.forEach(function (d) { %>
    <tr>
        <td><%- d.id %></td>
        <td><%- d.name %></td>
    </tr>
    <% }); %>
</table>

Ajax call in express:

app.get('/data', function (req, res) {
    res.send({ data: [
        { id: 5, name: 'Bill' },
        { id: 1, name: 'Bob' }
    ]});
});
Community
  • 1
  • 1
matth
  • 6,112
  • 4
  • 37
  • 43
  • Can you place the `getData` function inside the template itself or you'll have to create an external `script` file containing the function that you'll then inject inside your page? – AllJs Jul 09 '16 at 23:31
  • @AllJs, As far as I know you can place it within the script, however, I think it would be better organized if you had an external script file. – matth Jul 10 '16 at 05:11