0

I have a link on my site. When clicked it'll call a function that does a mongoose query. I'd like the results of that query to be sent to the same page in a variable without reloading the page. How do I do that? Right now it is just rendering the page again with new query result data.

// List comments for specified chapter id.
commentController.list = function (req, res) {
  var chapterId = req.params.chapterId;
  var query = { chapterId: chapterId };
  Chapter.find({ _id: chapterId }).then(function (chapter) {
    var chapter = chapter;
   Comment.find(query).then(function (data) {
  console.log(chapter);


    Chapter.find().then(function(chapters){
      return res.render({'chapterlinks', commentList: data, user: req.user, chapterq: chapter, chapters:chapters });

    })

});

}) };

1 Answer 1

1

You just need to make that request from your browser via AJAX:

https://www.w3schools.com/xml/ajax_intro.asp

This would be in the code for your client (browser), not the code for your server (nodejs).

UPDATE:

Here's a simple example, which uses jQuery to make things easier:

(1) create a function that performs and handles the ajax request

function getChapterLinks(chapterId) {
    $.ajax({
      url: "/chapterLinks/"+chapterId,
    }).done(function(data) {
      //here you should do something with data
      console.log(data);
    });
}

(2) bind that function to a DOM element's click event

$( "a#chapterLinks1" ).click(function() {
  getChapterLinks(1);
});

(3) make sure that DOM element is somewhere in you html

<a id="chapterLinks1">Get ChapterLinks 1</a>

Now when this a#chapterLinks1 element is clicked, it will use AJAX to fetch the response of /chaptersLink/1 from your server without reloading the page.


references:

http://api.jquery.com/jquery.ajax/

http://api.jquery.com/jquery.click/

Sign up to request clarification or add additional context in comments.

6 Comments

This is a link only answer. Please form a proper, complete answer using what you have linked to, if necessary. Links go dead and your answer will be useless. stackoverflow.com/help/how-to-answer
Perhaps I should have just simply answered "Use ajax", followed by a copy and pasted description of what it is, and omitted the link.
do i keep the res.render there? Where do i include the mongoose query in the ajax? calling that chapterlinks site is useless just gives me same data as before.
@user3542679 yeah keep it there. The mongoose query happens on the server when /chaptersLink/1 is requested, while the ajax happens within the webpage browser to make that request without reload the page. Hope that helps
yup figured it out yesterday. forgot to vote the answer. thnx!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.