Reputation: 535
this is my first Node application and I am trying to refresh the view based on filters applied by users. I have a view to show data in table as below
The code for the above is
async function getAll(req, res){
try {
if (req.session.loginError == true) {
return res.redirect('/');
}
//** logic to fetch data in sData[]
return res.view('pages/list', {data:sData});
}
catch(error){
sails.log.error('Controller#getAll :: error :', error);
return res.badRequest('Cannot fetch data at this time.' + error.stack);
}
}
The above works fine. Issue is if we select some date filters like fromDate & toDate, the data from backend is fetched correctly but the view isn't refreshed. I have put below code in ejs page to send filters to controller:
function search()
{
var searchData = {
fromDate : document.querySelector('#fromDate').value,
toDate : document.querySelector('#toDate').value,
status : document.querySelector('#status').value
};
var xmlhttp=new XMLHttpRequest();
url = "/admin/controller/filterData";
xmlhttp.open("POST",url,true);
xmlhttp.setRequestHeader('Content-Type', 'application/json;charset=UTF-8')
xmlhttp.send(JSON.stringify(searchData))
}
Created a new method in controller named filterData as below
async function filterData(req, res) {
try {
if (req.session.loginError == true) {
return res.redirect('/');
}
var sDate = Date.parse(req.param('fromDate'));
var eDate = Date.parse(req.param('toDate'));
var sta = req.param('status')
var data= await ****.find().where({ and: [{ start_date: { '>': sDate, '<': eDate } }, { status: sta }] }).populate("***").sort('createdAt DESC');
let sData = [];
_.forEach(d, function(data){
//logic to format data
sData.push(d);
});
return res.view('pages/list', {data:sData});
}
catch (error) {
sails.log.error('Controller#getfilterData :: error : ', error);
return res.redirect('/admin/***/getAll');
}
}
The sData[] gets filtered records but the page isn't getting refreshed with new data. I am not sure if we can refresh the view like this or need to send filtered data back to function in view and then have to refresh the table from there. Please advise.
Upvotes: 0
Views: 413
Reputation: 3526
You are sending XMLHttpRequest
which is an ajax
call. So the page won't reload at all. It's better to return a json response from server for /admin/controller/filterData
request and then populating the UI with ajax response.
Upvotes: 1