Reputation: 57
Im working with nodejs ,express and mongodb.And im working on cloud9 IDE
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("/",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 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
Upvotes: 3
Views: 70
Reputation: 1723
The text you want to be shown, will appear only after the button
is clicked, and once reloaded, you will have to click again (and the click will show the text, and trigger a reload, so the text will disappear again).
You need to have another button (That will not submit) to trigger this message. Or rather why not show initially (put this inline, inside the <h5>
tags) ?
You need to differentiate between 'no-data' or 'no-query. you can do it in the back-end, 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>
<% } %>
Upvotes: 1