Entering data from a form, retrieving data from a database, and displaying results

I'm working with nodejs, express and mongodb. And im working on the cloud area IDE

I want to create a page with a form that takes input from the user, searches for the relevant data from the database, and shows that the data is on the same page (after reload), and if no data is present then a specific response is displayed.

here is what i did -

Route-

app.get("/",function(req,res){
var asked = req.query.asked;
  Name.findOne({name:asked},function(err,foundAsked){
      if(err){console.log("ERROR!!!");}
      else{res.render("Landing.ejs",{foundAsked:foundAsked}); }
  });
 }); 

      

EJS file -

//Form takes name as input from the user

<form >
    <input type="text" name="asked" action="/" method="GET">
    <button class="button">Submit</button>
</form>



//If data is found last name is returned
<% if(foundAsked){ %>
    <h2 >  <%= foundAsked.Lastname %> </h2>
<% } %>


 //blank space stays there which is replaced by a response,if after 
   //submission nothing is found
<% if(!foundAsked){ %>
    <h5></h5> 
<% } %>

      

JS -

 $(".button").click(function(){

          $("h5").text("No data present");
 });

      

But the problem is that if there is no data, the answer is shown, but it remains only one time before the page is reloaded. I tried looking for an answer, but I couldn't find one. Please, help

+3


source to share


1 answer


The text you want to display will only appear after the button is clicked button

and after reboot you will have to click again (and the click will display the text and trigger the reload, so the text will disappear again).

You will need another button to trigger this message (This will not be sent). Or rather, why not show it first (put this inside, inside the tags <h5>

)?

You need to distinguish between "no-data" or "no-query". you can do it in the background, something similar to this:



app.get("/",function(req,res){
var asked = req.query.asked;
  Name.findOne({name:asked},function(err,foundAsked){
      if(err){console.log("ERROR!!!");}
      else{res.render("Landing.ejs",{foundAsked:foundAsked, asked: asked}); }
  });
 }); 

      

And then in Landing.ejs

:

<% if(!foundAsked && asked){ %>
        <h5>No data present</h5> 
  <% } %>

      

+1


source







All Articles