Wednesday 19 April 2017

Taking input from form, retrieving data from database and showing output

Im working with nodejs ,express and mongodb.

I want to create a page with a form which takes input from the user, search corresponding data from database and show that data on same page (after reloading) ,and if data isnt present then showing an specific response.

this is what i have done-

Route-

app.get("/xyz",function(req,res){
var asked = req.query.asked;
  Database.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 found ,the response is shown ,but it stays for only the time before the page reloads. I tried searching for an answer but i havnt found any.Please help



via Ravi Hooda

No comments:

Post a Comment