res.render() function rendering an ejs page doesn't refresh the UI, but the ejs page get called












0















I have a list of resources which needs to be filtered based on the location. I have a form to filter and on click of a button, the data is filtered based on the location. I have an AJAX request and it sends a post request to /filterresources and the data matching that criteria is also fetched from the db and the resourcefilter.ejs is rendered using res.render() as given below:



resourcefilter.js:



    router.post('/filterresources',function(req,res,next){
var category = req.body.category;
User.find({_id: {$ne: req.user._id}},(err,user) => {
if(err) throw err;
if(user)
{
db.findAll(Resource,{category:category})
.then(function(data){
res.render('resourcefilter',{title:"Steel Smiling",user:req.user,header:true,navbar:true,resources:data});
})
.catch(function(err){
next(err);
});
}
else {
throw(err);
}
});


});

The problem here is, as the records are fetched the UI doesn't get updated even when new ejs page is called. It still retains the previous page UI. But any console.log() statements in the new ejs page gets displayed.


resourcefilter.ejs: All console statements in this get printed without any issues but UI is not refreshed. Any help is much appreciated.



<% layout('layout/layout') %>


<div class="container user-form py-5">
<br>
<%if(user.role == 'Administrator'){ console.log(user.role);%>
<a href="/resourceupload" class="btn btn-outline-primary" style="float: right" ><span>Create Resource</span></a>
<%}%>
</br>
<span class="site-logo my-3">Our Resources</span>
<div class="col-12 col-lg-4 offset-lg-2" style="margin-left: 33%">
<form id="filter-resources" class="mt-5">
<div>
<select class="custom-select" name="category" id="category">
<option selected>Select a location:</option>
<option value="Pittsburgh">Pittsburgh</option>
<option value="Allegheny County">Allegheny County</option>
<option value="Pennsylvania">Pennsylvania</option>
<option value="Outside Pennsylvania">Outside Pennsylvania</option>
</select>
<input class="filter" name="filter-resources" type="submit" value="Filter">
</div>
</form>
</div>
</form>

<div class="container" style="margin-top: 2%;">

<div class="row">
<% for(var i=0;i<resources.length;i++){ console.log("Hello"+resources.length); %>
<div class="col-xs-12 col-sm-6 col-md-4">

<div class="image-flip" ontouchstart="this.classList.toggle('hover');">

<div class="mainflip">

<div class="frontside">

<div class="card-custom">
<% console.log("Image"+resources[i].image);%>
<div class="card-body text-center">
<img src="<%= resources[i].image %>" alt="" class="img-resources">
<div class="card-title"><b><%= resources[i].name%></b></div>
<div id="greetings" class="card-title"><textarea readonly class="resourceDesc"><%= resources[i].description%></textarea></div>
<a href ="#" class="card-title"></a>
<a href = <%= resources[i].website%> id="singlebutton" name="singlebutton" class="btn btn-primary">
Read More!</a>

<br></br> </div>
</div>
<br></br>
</div>



</div>

</div>
</div>


<% } %>

</div>
</div>
</div>


AJAX function to call to /filterresources:



function filter_resources(e) {
e.preventDefault();

var category = $('#category :selected').text();
console.log(category);
const button = this.children[this.children.length - 1];

//Form Handling with ajax

$.ajax({

url: '/filterresources',
type: 'post',
data: {category: category},
dataType: 'json',

});

function refreshDiv() {
document.getElementById("getelebyid").innerHTML = "Some <strong>HTML</strong> <em>string</em>" ;
}

}









share|improve this question

























  • Looking at your form I don't see an action being called to the /filterresources URL, also no method. Are you sending the request in a separate AJAX function?

    – Dmitriy
    Nov 15 '18 at 19:02













  • Yes the /filter resources is called using a separate AJAX function

    – AKrishnamurthi
    Nov 15 '18 at 19:07











  • Can you post the AJAX function?

    – Dmitriy
    Nov 15 '18 at 19:13











  • I have added the AJAX function above

    – AKrishnamurthi
    Nov 15 '18 at 19:16
















0















I have a list of resources which needs to be filtered based on the location. I have a form to filter and on click of a button, the data is filtered based on the location. I have an AJAX request and it sends a post request to /filterresources and the data matching that criteria is also fetched from the db and the resourcefilter.ejs is rendered using res.render() as given below:



resourcefilter.js:



    router.post('/filterresources',function(req,res,next){
var category = req.body.category;
User.find({_id: {$ne: req.user._id}},(err,user) => {
if(err) throw err;
if(user)
{
db.findAll(Resource,{category:category})
.then(function(data){
res.render('resourcefilter',{title:"Steel Smiling",user:req.user,header:true,navbar:true,resources:data});
})
.catch(function(err){
next(err);
});
}
else {
throw(err);
}
});


});

The problem here is, as the records are fetched the UI doesn't get updated even when new ejs page is called. It still retains the previous page UI. But any console.log() statements in the new ejs page gets displayed.


resourcefilter.ejs: All console statements in this get printed without any issues but UI is not refreshed. Any help is much appreciated.



<% layout('layout/layout') %>


<div class="container user-form py-5">
<br>
<%if(user.role == 'Administrator'){ console.log(user.role);%>
<a href="/resourceupload" class="btn btn-outline-primary" style="float: right" ><span>Create Resource</span></a>
<%}%>
</br>
<span class="site-logo my-3">Our Resources</span>
<div class="col-12 col-lg-4 offset-lg-2" style="margin-left: 33%">
<form id="filter-resources" class="mt-5">
<div>
<select class="custom-select" name="category" id="category">
<option selected>Select a location:</option>
<option value="Pittsburgh">Pittsburgh</option>
<option value="Allegheny County">Allegheny County</option>
<option value="Pennsylvania">Pennsylvania</option>
<option value="Outside Pennsylvania">Outside Pennsylvania</option>
</select>
<input class="filter" name="filter-resources" type="submit" value="Filter">
</div>
</form>
</div>
</form>

<div class="container" style="margin-top: 2%;">

<div class="row">
<% for(var i=0;i<resources.length;i++){ console.log("Hello"+resources.length); %>
<div class="col-xs-12 col-sm-6 col-md-4">

<div class="image-flip" ontouchstart="this.classList.toggle('hover');">

<div class="mainflip">

<div class="frontside">

<div class="card-custom">
<% console.log("Image"+resources[i].image);%>
<div class="card-body text-center">
<img src="<%= resources[i].image %>" alt="" class="img-resources">
<div class="card-title"><b><%= resources[i].name%></b></div>
<div id="greetings" class="card-title"><textarea readonly class="resourceDesc"><%= resources[i].description%></textarea></div>
<a href ="#" class="card-title"></a>
<a href = <%= resources[i].website%> id="singlebutton" name="singlebutton" class="btn btn-primary">
Read More!</a>

<br></br> </div>
</div>
<br></br>
</div>



</div>

</div>
</div>


<% } %>

</div>
</div>
</div>


AJAX function to call to /filterresources:



function filter_resources(e) {
e.preventDefault();

var category = $('#category :selected').text();
console.log(category);
const button = this.children[this.children.length - 1];

//Form Handling with ajax

$.ajax({

url: '/filterresources',
type: 'post',
data: {category: category},
dataType: 'json',

});

function refreshDiv() {
document.getElementById("getelebyid").innerHTML = "Some <strong>HTML</strong> <em>string</em>" ;
}

}









share|improve this question

























  • Looking at your form I don't see an action being called to the /filterresources URL, also no method. Are you sending the request in a separate AJAX function?

    – Dmitriy
    Nov 15 '18 at 19:02













  • Yes the /filter resources is called using a separate AJAX function

    – AKrishnamurthi
    Nov 15 '18 at 19:07











  • Can you post the AJAX function?

    – Dmitriy
    Nov 15 '18 at 19:13











  • I have added the AJAX function above

    – AKrishnamurthi
    Nov 15 '18 at 19:16














0












0








0








I have a list of resources which needs to be filtered based on the location. I have a form to filter and on click of a button, the data is filtered based on the location. I have an AJAX request and it sends a post request to /filterresources and the data matching that criteria is also fetched from the db and the resourcefilter.ejs is rendered using res.render() as given below:



resourcefilter.js:



    router.post('/filterresources',function(req,res,next){
var category = req.body.category;
User.find({_id: {$ne: req.user._id}},(err,user) => {
if(err) throw err;
if(user)
{
db.findAll(Resource,{category:category})
.then(function(data){
res.render('resourcefilter',{title:"Steel Smiling",user:req.user,header:true,navbar:true,resources:data});
})
.catch(function(err){
next(err);
});
}
else {
throw(err);
}
});


});

The problem here is, as the records are fetched the UI doesn't get updated even when new ejs page is called. It still retains the previous page UI. But any console.log() statements in the new ejs page gets displayed.


resourcefilter.ejs: All console statements in this get printed without any issues but UI is not refreshed. Any help is much appreciated.



<% layout('layout/layout') %>


<div class="container user-form py-5">
<br>
<%if(user.role == 'Administrator'){ console.log(user.role);%>
<a href="/resourceupload" class="btn btn-outline-primary" style="float: right" ><span>Create Resource</span></a>
<%}%>
</br>
<span class="site-logo my-3">Our Resources</span>
<div class="col-12 col-lg-4 offset-lg-2" style="margin-left: 33%">
<form id="filter-resources" class="mt-5">
<div>
<select class="custom-select" name="category" id="category">
<option selected>Select a location:</option>
<option value="Pittsburgh">Pittsburgh</option>
<option value="Allegheny County">Allegheny County</option>
<option value="Pennsylvania">Pennsylvania</option>
<option value="Outside Pennsylvania">Outside Pennsylvania</option>
</select>
<input class="filter" name="filter-resources" type="submit" value="Filter">
</div>
</form>
</div>
</form>

<div class="container" style="margin-top: 2%;">

<div class="row">
<% for(var i=0;i<resources.length;i++){ console.log("Hello"+resources.length); %>
<div class="col-xs-12 col-sm-6 col-md-4">

<div class="image-flip" ontouchstart="this.classList.toggle('hover');">

<div class="mainflip">

<div class="frontside">

<div class="card-custom">
<% console.log("Image"+resources[i].image);%>
<div class="card-body text-center">
<img src="<%= resources[i].image %>" alt="" class="img-resources">
<div class="card-title"><b><%= resources[i].name%></b></div>
<div id="greetings" class="card-title"><textarea readonly class="resourceDesc"><%= resources[i].description%></textarea></div>
<a href ="#" class="card-title"></a>
<a href = <%= resources[i].website%> id="singlebutton" name="singlebutton" class="btn btn-primary">
Read More!</a>

<br></br> </div>
</div>
<br></br>
</div>



</div>

</div>
</div>


<% } %>

</div>
</div>
</div>


AJAX function to call to /filterresources:



function filter_resources(e) {
e.preventDefault();

var category = $('#category :selected').text();
console.log(category);
const button = this.children[this.children.length - 1];

//Form Handling with ajax

$.ajax({

url: '/filterresources',
type: 'post',
data: {category: category},
dataType: 'json',

});

function refreshDiv() {
document.getElementById("getelebyid").innerHTML = "Some <strong>HTML</strong> <em>string</em>" ;
}

}









share|improve this question
















I have a list of resources which needs to be filtered based on the location. I have a form to filter and on click of a button, the data is filtered based on the location. I have an AJAX request and it sends a post request to /filterresources and the data matching that criteria is also fetched from the db and the resourcefilter.ejs is rendered using res.render() as given below:



resourcefilter.js:



    router.post('/filterresources',function(req,res,next){
var category = req.body.category;
User.find({_id: {$ne: req.user._id}},(err,user) => {
if(err) throw err;
if(user)
{
db.findAll(Resource,{category:category})
.then(function(data){
res.render('resourcefilter',{title:"Steel Smiling",user:req.user,header:true,navbar:true,resources:data});
})
.catch(function(err){
next(err);
});
}
else {
throw(err);
}
});


});

The problem here is, as the records are fetched the UI doesn't get updated even when new ejs page is called. It still retains the previous page UI. But any console.log() statements in the new ejs page gets displayed.


resourcefilter.ejs: All console statements in this get printed without any issues but UI is not refreshed. Any help is much appreciated.



<% layout('layout/layout') %>


<div class="container user-form py-5">
<br>
<%if(user.role == 'Administrator'){ console.log(user.role);%>
<a href="/resourceupload" class="btn btn-outline-primary" style="float: right" ><span>Create Resource</span></a>
<%}%>
</br>
<span class="site-logo my-3">Our Resources</span>
<div class="col-12 col-lg-4 offset-lg-2" style="margin-left: 33%">
<form id="filter-resources" class="mt-5">
<div>
<select class="custom-select" name="category" id="category">
<option selected>Select a location:</option>
<option value="Pittsburgh">Pittsburgh</option>
<option value="Allegheny County">Allegheny County</option>
<option value="Pennsylvania">Pennsylvania</option>
<option value="Outside Pennsylvania">Outside Pennsylvania</option>
</select>
<input class="filter" name="filter-resources" type="submit" value="Filter">
</div>
</form>
</div>
</form>

<div class="container" style="margin-top: 2%;">

<div class="row">
<% for(var i=0;i<resources.length;i++){ console.log("Hello"+resources.length); %>
<div class="col-xs-12 col-sm-6 col-md-4">

<div class="image-flip" ontouchstart="this.classList.toggle('hover');">

<div class="mainflip">

<div class="frontside">

<div class="card-custom">
<% console.log("Image"+resources[i].image);%>
<div class="card-body text-center">
<img src="<%= resources[i].image %>" alt="" class="img-resources">
<div class="card-title"><b><%= resources[i].name%></b></div>
<div id="greetings" class="card-title"><textarea readonly class="resourceDesc"><%= resources[i].description%></textarea></div>
<a href ="#" class="card-title"></a>
<a href = <%= resources[i].website%> id="singlebutton" name="singlebutton" class="btn btn-primary">
Read More!</a>

<br></br> </div>
</div>
<br></br>
</div>



</div>

</div>
</div>


<% } %>

</div>
</div>
</div>


AJAX function to call to /filterresources:



function filter_resources(e) {
e.preventDefault();

var category = $('#category :selected').text();
console.log(category);
const button = this.children[this.children.length - 1];

//Form Handling with ajax

$.ajax({

url: '/filterresources',
type: 'post',
data: {category: category},
dataType: 'json',

});

function refreshDiv() {
document.getElementById("getelebyid").innerHTML = "Some <strong>HTML</strong> <em>string</em>" ;
}

}






javascript node.js ejs






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 15 '18 at 19:16







AKrishnamurthi

















asked Nov 15 '18 at 18:54









AKrishnamurthiAKrishnamurthi

186




186













  • Looking at your form I don't see an action being called to the /filterresources URL, also no method. Are you sending the request in a separate AJAX function?

    – Dmitriy
    Nov 15 '18 at 19:02













  • Yes the /filter resources is called using a separate AJAX function

    – AKrishnamurthi
    Nov 15 '18 at 19:07











  • Can you post the AJAX function?

    – Dmitriy
    Nov 15 '18 at 19:13











  • I have added the AJAX function above

    – AKrishnamurthi
    Nov 15 '18 at 19:16



















  • Looking at your form I don't see an action being called to the /filterresources URL, also no method. Are you sending the request in a separate AJAX function?

    – Dmitriy
    Nov 15 '18 at 19:02













  • Yes the /filter resources is called using a separate AJAX function

    – AKrishnamurthi
    Nov 15 '18 at 19:07











  • Can you post the AJAX function?

    – Dmitriy
    Nov 15 '18 at 19:13











  • I have added the AJAX function above

    – AKrishnamurthi
    Nov 15 '18 at 19:16

















Looking at your form I don't see an action being called to the /filterresources URL, also no method. Are you sending the request in a separate AJAX function?

– Dmitriy
Nov 15 '18 at 19:02







Looking at your form I don't see an action being called to the /filterresources URL, also no method. Are you sending the request in a separate AJAX function?

– Dmitriy
Nov 15 '18 at 19:02















Yes the /filter resources is called using a separate AJAX function

– AKrishnamurthi
Nov 15 '18 at 19:07





Yes the /filter resources is called using a separate AJAX function

– AKrishnamurthi
Nov 15 '18 at 19:07













Can you post the AJAX function?

– Dmitriy
Nov 15 '18 at 19:13





Can you post the AJAX function?

– Dmitriy
Nov 15 '18 at 19:13













I have added the AJAX function above

– AKrishnamurthi
Nov 15 '18 at 19:16





I have added the AJAX function above

– AKrishnamurthi
Nov 15 '18 at 19:16












3 Answers
3






active

oldest

votes


















2














Your ejs, js and html code are correct, the problem is that your AJAX function does not refresh the page's content, it only retrieves the content. There are 2 solutions: Either, in the EJS, change from "render" to "send" and then in the AJAX callback use the value returned as innerHTML for some element, or do a form submit, and not a jquery post. The form submit will cause a page reload.






share|improve this answer































    2














    If you don't have any errors from your server you can do a workaround with the front end:



    $.ajax({

    url: '/filterresources',
    type: 'post',
    data: {category: category},
    dataType: 'json',

    }).then(() => location.reload());


    That will refresh your page when the request finishes.






    share|improve this answer































      0














      location.reload() didn't work in this context because the filtered data needs to be passed on to the page. Hence, instead of using res.render(), i used res.send as suggested. Please find the below code:



      filterresources.js



      router.post('/filterresources',function(req,res,next){
      var category = req.body.category;
      User.find({_id: {$ne: req.user._id}},(err,user) => {
      if(err) throw err;
      if(user)
      {
      var user = req.user._id;
      console.log(user);
      db.findAll(Resource,{category:category})
      .then(function(data){
      res.send({msg: data, success: true,user: user });
      })
      .catch(function(err){
      next(err);
      });
      }
      else {
      throw(err);
      }

      });
      });


      AJAX function:



      function filter_resources(e) {
      e.preventDefault();

      var category = $('#category :selected').text();
      console.log(category);
      const button = this.children[this.children.length - 1];

      //Form Handling with ajax

      $.ajax({
      url: '/filterresources',
      type: 'post',
      data: {category: category},
      dataType: 'json',
      success: function (response) {
      if (!response.success) {
      window.alert(response.msg);
      }
      if (response.success) {
      var resource = response.msg;
      var userInfo = response.user;
      $('#resfilter').html(""); // reset the contents in the div
      var html = `<div class="row">`;
      for(var i=0;i<resource.length;i++) {
      html += `<div class="col-xs-12 col-sm-6 col-md-4">
      <div class="image-flip" ontouchstart="this.classList.toggle('hover');">
      <div class="mainflip"> <div class="frontside"> <div class="card-custom">
      <div class="card-body text-center">`;
      html += `<img src="${resource[i].image}" alt="Mental Health Resource" class="img-resources">`;
      html += `<div class="card-title"><b>${resource[i].name}</b></div>`;
      html += `<div id="greetings" class="card-title"><textarea readonly class="resourceDesc">${resource[i].description}</textarea></div>`;
      html += `<a href ="#" class="card-title"></a>`;
      html += `<a href = ${resource[i].website} id="singlebutton" name="singlebutton" class="btn btn-primary">Read More!</a>`;
      html += `<br>`;
      html += `</br></div></div><br></br></div></div></div></div>`;
      }
      html += `</div></div></div></div>`;
      }
      document.querySelector('#resfilter').innerHTML = html; // add the html content to the div which was earlier reset
      }
      })
      }





      share|improve this answer























        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53326172%2fres-render-function-rendering-an-ejs-page-doesnt-refresh-the-ui-but-the-ejs%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        2














        Your ejs, js and html code are correct, the problem is that your AJAX function does not refresh the page's content, it only retrieves the content. There are 2 solutions: Either, in the EJS, change from "render" to "send" and then in the AJAX callback use the value returned as innerHTML for some element, or do a form submit, and not a jquery post. The form submit will cause a page reload.






        share|improve this answer




























          2














          Your ejs, js and html code are correct, the problem is that your AJAX function does not refresh the page's content, it only retrieves the content. There are 2 solutions: Either, in the EJS, change from "render" to "send" and then in the AJAX callback use the value returned as innerHTML for some element, or do a form submit, and not a jquery post. The form submit will cause a page reload.






          share|improve this answer


























            2












            2








            2







            Your ejs, js and html code are correct, the problem is that your AJAX function does not refresh the page's content, it only retrieves the content. There are 2 solutions: Either, in the EJS, change from "render" to "send" and then in the AJAX callback use the value returned as innerHTML for some element, or do a form submit, and not a jquery post. The form submit will cause a page reload.






            share|improve this answer













            Your ejs, js and html code are correct, the problem is that your AJAX function does not refresh the page's content, it only retrieves the content. There are 2 solutions: Either, in the EJS, change from "render" to "send" and then in the AJAX callback use the value returned as innerHTML for some element, or do a form submit, and not a jquery post. The form submit will cause a page reload.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 15 '18 at 19:32









            Sergio FloresSergio Flores

            1126




            1126

























                2














                If you don't have any errors from your server you can do a workaround with the front end:



                $.ajax({

                url: '/filterresources',
                type: 'post',
                data: {category: category},
                dataType: 'json',

                }).then(() => location.reload());


                That will refresh your page when the request finishes.






                share|improve this answer




























                  2














                  If you don't have any errors from your server you can do a workaround with the front end:



                  $.ajax({

                  url: '/filterresources',
                  type: 'post',
                  data: {category: category},
                  dataType: 'json',

                  }).then(() => location.reload());


                  That will refresh your page when the request finishes.






                  share|improve this answer


























                    2












                    2








                    2







                    If you don't have any errors from your server you can do a workaround with the front end:



                    $.ajax({

                    url: '/filterresources',
                    type: 'post',
                    data: {category: category},
                    dataType: 'json',

                    }).then(() => location.reload());


                    That will refresh your page when the request finishes.






                    share|improve this answer













                    If you don't have any errors from your server you can do a workaround with the front end:



                    $.ajax({

                    url: '/filterresources',
                    type: 'post',
                    data: {category: category},
                    dataType: 'json',

                    }).then(() => location.reload());


                    That will refresh your page when the request finishes.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 15 '18 at 19:27









                    DmitriyDmitriy

                    611216




                    611216























                        0














                        location.reload() didn't work in this context because the filtered data needs to be passed on to the page. Hence, instead of using res.render(), i used res.send as suggested. Please find the below code:



                        filterresources.js



                        router.post('/filterresources',function(req,res,next){
                        var category = req.body.category;
                        User.find({_id: {$ne: req.user._id}},(err,user) => {
                        if(err) throw err;
                        if(user)
                        {
                        var user = req.user._id;
                        console.log(user);
                        db.findAll(Resource,{category:category})
                        .then(function(data){
                        res.send({msg: data, success: true,user: user });
                        })
                        .catch(function(err){
                        next(err);
                        });
                        }
                        else {
                        throw(err);
                        }

                        });
                        });


                        AJAX function:



                        function filter_resources(e) {
                        e.preventDefault();

                        var category = $('#category :selected').text();
                        console.log(category);
                        const button = this.children[this.children.length - 1];

                        //Form Handling with ajax

                        $.ajax({
                        url: '/filterresources',
                        type: 'post',
                        data: {category: category},
                        dataType: 'json',
                        success: function (response) {
                        if (!response.success) {
                        window.alert(response.msg);
                        }
                        if (response.success) {
                        var resource = response.msg;
                        var userInfo = response.user;
                        $('#resfilter').html(""); // reset the contents in the div
                        var html = `<div class="row">`;
                        for(var i=0;i<resource.length;i++) {
                        html += `<div class="col-xs-12 col-sm-6 col-md-4">
                        <div class="image-flip" ontouchstart="this.classList.toggle('hover');">
                        <div class="mainflip"> <div class="frontside"> <div class="card-custom">
                        <div class="card-body text-center">`;
                        html += `<img src="${resource[i].image}" alt="Mental Health Resource" class="img-resources">`;
                        html += `<div class="card-title"><b>${resource[i].name}</b></div>`;
                        html += `<div id="greetings" class="card-title"><textarea readonly class="resourceDesc">${resource[i].description}</textarea></div>`;
                        html += `<a href ="#" class="card-title"></a>`;
                        html += `<a href = ${resource[i].website} id="singlebutton" name="singlebutton" class="btn btn-primary">Read More!</a>`;
                        html += `<br>`;
                        html += `</br></div></div><br></br></div></div></div></div>`;
                        }
                        html += `</div></div></div></div>`;
                        }
                        document.querySelector('#resfilter').innerHTML = html; // add the html content to the div which was earlier reset
                        }
                        })
                        }





                        share|improve this answer




























                          0














                          location.reload() didn't work in this context because the filtered data needs to be passed on to the page. Hence, instead of using res.render(), i used res.send as suggested. Please find the below code:



                          filterresources.js



                          router.post('/filterresources',function(req,res,next){
                          var category = req.body.category;
                          User.find({_id: {$ne: req.user._id}},(err,user) => {
                          if(err) throw err;
                          if(user)
                          {
                          var user = req.user._id;
                          console.log(user);
                          db.findAll(Resource,{category:category})
                          .then(function(data){
                          res.send({msg: data, success: true,user: user });
                          })
                          .catch(function(err){
                          next(err);
                          });
                          }
                          else {
                          throw(err);
                          }

                          });
                          });


                          AJAX function:



                          function filter_resources(e) {
                          e.preventDefault();

                          var category = $('#category :selected').text();
                          console.log(category);
                          const button = this.children[this.children.length - 1];

                          //Form Handling with ajax

                          $.ajax({
                          url: '/filterresources',
                          type: 'post',
                          data: {category: category},
                          dataType: 'json',
                          success: function (response) {
                          if (!response.success) {
                          window.alert(response.msg);
                          }
                          if (response.success) {
                          var resource = response.msg;
                          var userInfo = response.user;
                          $('#resfilter').html(""); // reset the contents in the div
                          var html = `<div class="row">`;
                          for(var i=0;i<resource.length;i++) {
                          html += `<div class="col-xs-12 col-sm-6 col-md-4">
                          <div class="image-flip" ontouchstart="this.classList.toggle('hover');">
                          <div class="mainflip"> <div class="frontside"> <div class="card-custom">
                          <div class="card-body text-center">`;
                          html += `<img src="${resource[i].image}" alt="Mental Health Resource" class="img-resources">`;
                          html += `<div class="card-title"><b>${resource[i].name}</b></div>`;
                          html += `<div id="greetings" class="card-title"><textarea readonly class="resourceDesc">${resource[i].description}</textarea></div>`;
                          html += `<a href ="#" class="card-title"></a>`;
                          html += `<a href = ${resource[i].website} id="singlebutton" name="singlebutton" class="btn btn-primary">Read More!</a>`;
                          html += `<br>`;
                          html += `</br></div></div><br></br></div></div></div></div>`;
                          }
                          html += `</div></div></div></div>`;
                          }
                          document.querySelector('#resfilter').innerHTML = html; // add the html content to the div which was earlier reset
                          }
                          })
                          }





                          share|improve this answer


























                            0












                            0








                            0







                            location.reload() didn't work in this context because the filtered data needs to be passed on to the page. Hence, instead of using res.render(), i used res.send as suggested. Please find the below code:



                            filterresources.js



                            router.post('/filterresources',function(req,res,next){
                            var category = req.body.category;
                            User.find({_id: {$ne: req.user._id}},(err,user) => {
                            if(err) throw err;
                            if(user)
                            {
                            var user = req.user._id;
                            console.log(user);
                            db.findAll(Resource,{category:category})
                            .then(function(data){
                            res.send({msg: data, success: true,user: user });
                            })
                            .catch(function(err){
                            next(err);
                            });
                            }
                            else {
                            throw(err);
                            }

                            });
                            });


                            AJAX function:



                            function filter_resources(e) {
                            e.preventDefault();

                            var category = $('#category :selected').text();
                            console.log(category);
                            const button = this.children[this.children.length - 1];

                            //Form Handling with ajax

                            $.ajax({
                            url: '/filterresources',
                            type: 'post',
                            data: {category: category},
                            dataType: 'json',
                            success: function (response) {
                            if (!response.success) {
                            window.alert(response.msg);
                            }
                            if (response.success) {
                            var resource = response.msg;
                            var userInfo = response.user;
                            $('#resfilter').html(""); // reset the contents in the div
                            var html = `<div class="row">`;
                            for(var i=0;i<resource.length;i++) {
                            html += `<div class="col-xs-12 col-sm-6 col-md-4">
                            <div class="image-flip" ontouchstart="this.classList.toggle('hover');">
                            <div class="mainflip"> <div class="frontside"> <div class="card-custom">
                            <div class="card-body text-center">`;
                            html += `<img src="${resource[i].image}" alt="Mental Health Resource" class="img-resources">`;
                            html += `<div class="card-title"><b>${resource[i].name}</b></div>`;
                            html += `<div id="greetings" class="card-title"><textarea readonly class="resourceDesc">${resource[i].description}</textarea></div>`;
                            html += `<a href ="#" class="card-title"></a>`;
                            html += `<a href = ${resource[i].website} id="singlebutton" name="singlebutton" class="btn btn-primary">Read More!</a>`;
                            html += `<br>`;
                            html += `</br></div></div><br></br></div></div></div></div>`;
                            }
                            html += `</div></div></div></div>`;
                            }
                            document.querySelector('#resfilter').innerHTML = html; // add the html content to the div which was earlier reset
                            }
                            })
                            }





                            share|improve this answer













                            location.reload() didn't work in this context because the filtered data needs to be passed on to the page. Hence, instead of using res.render(), i used res.send as suggested. Please find the below code:



                            filterresources.js



                            router.post('/filterresources',function(req,res,next){
                            var category = req.body.category;
                            User.find({_id: {$ne: req.user._id}},(err,user) => {
                            if(err) throw err;
                            if(user)
                            {
                            var user = req.user._id;
                            console.log(user);
                            db.findAll(Resource,{category:category})
                            .then(function(data){
                            res.send({msg: data, success: true,user: user });
                            })
                            .catch(function(err){
                            next(err);
                            });
                            }
                            else {
                            throw(err);
                            }

                            });
                            });


                            AJAX function:



                            function filter_resources(e) {
                            e.preventDefault();

                            var category = $('#category :selected').text();
                            console.log(category);
                            const button = this.children[this.children.length - 1];

                            //Form Handling with ajax

                            $.ajax({
                            url: '/filterresources',
                            type: 'post',
                            data: {category: category},
                            dataType: 'json',
                            success: function (response) {
                            if (!response.success) {
                            window.alert(response.msg);
                            }
                            if (response.success) {
                            var resource = response.msg;
                            var userInfo = response.user;
                            $('#resfilter').html(""); // reset the contents in the div
                            var html = `<div class="row">`;
                            for(var i=0;i<resource.length;i++) {
                            html += `<div class="col-xs-12 col-sm-6 col-md-4">
                            <div class="image-flip" ontouchstart="this.classList.toggle('hover');">
                            <div class="mainflip"> <div class="frontside"> <div class="card-custom">
                            <div class="card-body text-center">`;
                            html += `<img src="${resource[i].image}" alt="Mental Health Resource" class="img-resources">`;
                            html += `<div class="card-title"><b>${resource[i].name}</b></div>`;
                            html += `<div id="greetings" class="card-title"><textarea readonly class="resourceDesc">${resource[i].description}</textarea></div>`;
                            html += `<a href ="#" class="card-title"></a>`;
                            html += `<a href = ${resource[i].website} id="singlebutton" name="singlebutton" class="btn btn-primary">Read More!</a>`;
                            html += `<br>`;
                            html += `</br></div></div><br></br></div></div></div></div>`;
                            }
                            html += `</div></div></div></div>`;
                            }
                            document.querySelector('#resfilter').innerHTML = html; // add the html content to the div which was earlier reset
                            }
                            })
                            }






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Nov 16 '18 at 3:06









                            AKrishnamurthiAKrishnamurthi

                            186




                            186






























                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53326172%2fres-render-function-rendering-an-ejs-page-doesnt-refresh-the-ui-but-the-ejs%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                Bressuire

                                Vorschmack

                                Quarantine