Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ajax

node.js

ejs

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)" >
like image 987
Anirudh Avatar asked May 23 '17 06:05

Anirudh


People also ask

How do I use EJS templating?

Steps to run the program:After creating all the files go to the root directory of your project folder. Run command prompt in this directory. Type node file_name. js command to run your program and see the output as displayed.


1 Answers

Your strategy is correct!

Just need to fix some small things:

  • Routes between server and client should match
  • Ajax API should return data in json format

App.js file

app.get('/admin/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.json({data:data});
    });

});

Hope that it can help :)

like image 156
haotang Avatar answered Oct 01 '22 16:10

haotang