Collecting information from form submissions, accessing data from the database, and displaying the results

I am currently working on a project using nodejs, express, and mongodb within the cloud9 IDE.

My goal is to create a page with a form that allows users to input data, search for corresponding information in the database, and display that data on the same page after reloading. If the data is not found, I'd like to show a specific response.

This is what I have accomplished so far:

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");
 });

However, I'm experiencing an issue where the response indicating no data found only appears briefly before the page reloads. I haven't been able to find a solution despite researching it. Any help would be appreciated.

Answer №1

After a click on the button, the text you desire to see will be revealed. However, upon reloading, you must click again to view it (each click will display the text and prompt a reload, causing the text to vanish once more).

To activate this message, another button that does not submit is required. Alternatively, why not have it displayed initially (insert it inline within the <h5> tags)?

It is important to distinguish between 'no-data' and 'no-query'. This can be achieved in the backend, for example:

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}); }
  });
 }); 

Subsequently, in Landing.ejs:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

jquery is unable to locate text

UPDATE: I have recently implemented a function that calculates and displays the length of a certain element, but it currently requires user interaction to trigger it: function check() { alert($("#currentTechnicalPositions").html().length); } After s ...

Attempt the axios request again if the response is null or missing

await axios .post( executeBatch, { headers: { "Content-Type": "application/json", "x-access-token": localStorage.getItem("token"), }, } ) .then( ...

Exploring the possibilities of utilizing React server components in my project

I am interested in experimenting with the new React API for making server-side component calls. However, I am unable to find any information on how to begin a project using server components. In an example of source code that I stumbled upon, it mentioned ...

Making a POST request across domains without relying on any third-party frameworks

Is it possible to create a cross-domain request using vanilla JavaScript without relying on frameworks like jQuery? I am looking to send a JSON to a service on a different domain and receive the response using a callback function. Can this be done solely ...

What is the method for establishing session or cookie in an HTTPS request to a specific URL?

When making an HTTPS GET request in Node.js to a specific URL, it is necessary to include the session cookie. In this case, I already have the value of the cookie that needs to be sent. var URL = require('url-parse'); var appurl = "https://test ...

Utilize Next.js to send an image to an email by leveraging the renderToString function on the API routes

I need help with sending styled emails that contain images. Currently, I am utilizing the renderToString method to pass props into my component. So far, everything is functioning correctly in the API routes. mport client from "@/lib/prisma"; im ...

Struggling to find the right alignment for my Bootstrap card design

I'm attempting to center a card in the middle of the screen. While I was able to horizontally center it using mx-auto, I'm facing difficulties with vertical centering. I tried using mt-3 to add margin-top to the card, but it only gives me about ...

How to print a specific div from an HTML page with custom dimensions

I am looking for a solution to print just a specific div from a website with dimensions of 3"x5". Despite setting up the print button, the entire page continues to print every time. Is there a way to hide all non-div content in print preview? CSS .wholeb ...

What is the best way to determine the current version of a specific Node.js package?

How can I retrieve the current version of a particular package from package-lock.json or yarn.lock files, which will be installed? Is there any API available (not a command line tool) to ensure future independence from format changes? For instance, I wou ...

Nightwatch.js feature not functioning properly in a 'closing' manner

I'm facing an issue where I need to execute a function at the beginning of my test before proceeding with the rest of the test steps. Here is the custom command I am using, named internalAdviceLinksHtml: const solr = require('solr-client') ...

Arrows indicating the direction of a LineString feature in Openlayers 4

I'm attempting to create a LineString with arrows at the end of each line to indicate the direction of the route. I found an example on the official site: The example code in the link creates arrows through user drawing, but I need arrows for a give ...

Instructions for adding username/password authentication using Express ntlm

Attempting to set up username and password authentication using Express-ntlm. I've included the following code as middleware: app.use( ntlm({ domain: '<domainname>', domaincontroller: '<ldap url>', })); I haven't ...

Placing an eye icon on the password input field for optimal visibility and positioning

I am currently working on a Node.js project and I am attempting to incorporate an eye icon using Bootstrap into the password input field for visibility. Below is the code snippet of my input field: <div class="container"> <form ...

Using HTML5 and CSS for 3D transformations along with stacking divs to create a unique accordion

Is there a way to stack divs vertically above each other and use CSS3 3D transforms to create a folding effect between them? I've tried rotating the divs on their X axis, but it leaves gaps between each div because they don't collapse into each o ...

Having trouble running Angular CLI in Git Bash terminal on Windows?

I have been attempting to set up the Angular CLI using npm. Currently, my node version is v11.2.0 and my npm version is 6.4.1. Upon executing the command npm install -g @angular/cli, the output I receive is as follows: C:\Users\Mark O'Hare ...

Understanding how to effectively conduct unit tests on the 'resolve' property within an Angular-UI Bootstrap Modal component is essential for ensuring the functionality and

I'm currently working on building a unit test that verifies the correct variable is being passed to the resolve property within the ui.bootstrap.modal from Angular-UI Bootstrap components. Here's my progress so far: // Controller angular.module( ...

Expanding a feature that modifies the CSS properties of every input element

Creating a text tracking (letter-spacing) demonstration where range sliders are used to update CSS properties. I'm looking to improve the functionality so that the labels also update dynamically, without repeating output2.textContent = this.value;. An ...

Struggling to transfer information between POST and GET requests in Node/Express

Just diving into node/express, currently developing a weather application that receives location data from a form submission <form method="POST" action="/"> <input id="input" type="text" name="city" placeholder="Search by city or zip code" /> ...

Tips for maintaining circular references when converting a JavaScript object to JSON string format

Currently, I am developing a filetree-like object that has a unique structure: var myObject = { 'name':'foo', 'contains': {'thisObject': myObject,'parentObject': /* the object that contains the cur ...

Using AngularJS, I can bind the ng-model directive to asynchronously update and retrieve data from

I am currently working with Angular to develop a preferences page. Essentially, I have a field in a mysql table on my server which I want to connect my textbox to using ng-model through an asynchronous xhr request for setting and fetching data. I attempt ...