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)" >
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.
Your strategy is correct!
Just need to fix some small things:
server
and client
should matchjson
formatApp.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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With