A
A
Alexander Koshelev2018-10-06 11:49:00
Node.js
Alexander Koshelev, 2018-10-06 11:49:00

How to make a search in node.js on a page with a selection from the database and then display the result?

Good afternoon please help!
Briefly. Here is the .ejs page. Here the user enters data in the field and clicks the find button

<div id="search-username">
        <p class="search-title">Find username</p>
            <input type="text" id="search-your-username" class="input-search" name="search" placeholder="Search for...">
            <button class="button-search" id="button-search-username">SEARCH</button>
    </div>

Further it is the same, but the code is in script tags.
As soon as the user clicked the find button, I get the data of his request in the id variable.
$(document).ready(function(){
          $(".button-search").on("click", function(){
            var id = $("#search-your-username").val();
          })
        });

Next, I need to make a request to the database for the presence of the entered data and display the result on the same page,
here is the file with the route of this page
router.get('/search', async (req, res) => {
  const isUser = User.findOne({
  });
  res.render('search', {isUser});
});

At first I tried to write User.findAll instead of User.findOne and render this variable consisting of ALL database data to the ejs file and then used for and if to find the necessary data, everything was normal and displayed, but there were some nuances due to which I had to abandon this method.
Then I tried to add Post to the routes and wrapped the search input in a form, then I already checked for the presence of data in the database in the router.post (...) code itself, and in the end it turned out that when I sent a post request, the first time I clicked the button " Find" searched from the database (and nothing was found), and then only the post method went, and only if you press the button 2 times with the same query data, then the value found from the database was displayed, so the method worked even worse!
now I decided to assign a variable (request data from the user) to the variable ID, then I need to either pass it somehow to routes.js where the search will take place from the database and then give it back, or pass this ID variable through the search in the database directly in the ejs file, but how then to connect the js file in which the work with the database is going on?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question