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

Tips for finding information within a table using HTML

My task involves creating a table with the option for users to search data within it. However, I have encountered an issue where I am only able to search for data in the first row of the table. <table style="width:100%" id="table"> <tr> ...

Selecting radio button does not update corresponding label

I am having an issue with setting a radio button as checked. In the example snippet, it works perfectly fine but on my localhost, it is not working. Even though the input gets checked, the label does not change. Surprisingly, if I set another radio button ...

There is a SyntaxError due to an unexpected token "o" in the JSON data. It is not a valid JSON format

This code is designed to check an XML file to see if the email or login inputted by a user is already in use, and then provide a JSON response. The AJAX code for this functionality is as follows: $.ajax({ type: 'post', dat ...

Automatically submit a PHP form if the input text box is left blank

I need a way to automatically refresh the data on my page when the textbox is empty. Manually submitting the form works perfectly, but I want it to happen automatically if the textbox is empty. The catch is that I don't want the form to submit while t ...

Insufficient memory causing electron-builder to encounter issues

The main issue at hand is that while trying to build and run an Electron application containing a webpack React app, we're facing challenges related to running out of heap memory. This problem has cropped up recently without any apparent correlation t ...

Is there a way I can alter the font style of the word 'Logout'?

Hey, does anyone have a solution for changing the text color of "Logout!" to white? echo "Welcome, ".$_SESSION['username']."!<br><a href='logout.php'>Logout!"; <font color="#ffffff">your answer</font> ...

Create a gulp task within a callback function that is initiated by calling the filesystem.readdir

When attempting to read the name of the first folder from a directory, and then defining gulp tasks based on that folder, I am encountering an issue. Specifically, after defining a task inside the callback function, the tasks do not get properly defined. T ...

What is the best way to create spacing between images in a CSS image slider?

UPDATE: I've made significant progress by modifying the code provided in the link below. I am very close to achieving my desired result, but there are parts of it that still puzzle me. The transition now has spacing on both sides and the hidden space ...

Using jQuery to determine if the child element is a <ul> tag

HTML: <ul class="menu"> <li><a href="http://example.com">Text</a> <ul> <li><a href="http://example.com">Text</a> <li><a href="#">Text</a> <li><a href="# ...

Speedy Guide to Referencing Variables in JavaScript

I'm hoping for some clarification on this topic. Let's imagine I have 2 global variables: var myarray=[1,3,5,7,9],hold; and then I execute the following code: function setup() { alert (myarray[0]);//displays 1 hold=myarray; alert (hold);//seem ...

I am experiencing issues with the rendering of my q-btn elements in Quasar and they are

I recently started using Quasar and encountered an issue with my q-btn component buttons displaying white backgrounds at random, despite having added a background-color in the external stylesheets. Here are some examples of this perplexing problem: The e ...

The server's response is unpredictable, causing Json.Parse to fail intermittently

I have encountered a strange issue that is really frustrating. It all started when I noticed that my Json.Parse function failed intermittently. Here is the code snippet in question: const Info = JSON.parse(response); this.onInfoUpdate(Info.InfoConfig[0]); ...

Design an arrangement using div elements and CSS styling

Creating a layout for a website can be challenging. I am using three div tags - container, left, and right. My goal is to have the left side fixed-width for navigation, while the right side displays dynamic content loaded from a database. However, I'm ...

Improving sharing functionality across multiple VuGen scripts executed through Performance Center

I have multiple VuGen scripts that utilize the Web/HTTP protocol with javascript. Currently, I am using VuGen 12.53 (patch 4) and have a common login.js action in all of my scripts. Whenever I need to make changes to the login action, I have to update ever ...

Masking of the Navigation Button

I designed a responsive navigation bar, but in mobile view, the menu icon is being hidden by the menu headings when displayed. Check out the scenario below with a provided CodePen link. I attempted to adjust padding and float properties without success. An ...

Discovering the file extension and ensuring its validity when imported from Google Drive

I am facing an issue with a select tag that has 3 options: powerpoint, pdf, and spreadsheet. When uploading from Google Drive, there is no validation in place, so I can give a ppt link to the pdf option and it will still upload. Can someone help me with va ...

What steps are needed to configure ESLint to exclusively analyze .ts files?

I need ESLint to exclusively focus on processing .ts files and not .js files. In order to achieve that, I made a .eslintignore file and included the following lines: *.js **/*.js Nevertheless, it appears that ESLint is disregarding this file. Is there so ...

What are some of the techniques for customizing the DOM generated by material-ui in ReactJS?

Is there a way to style the dynamically created DOM elements from material-ui? I'm currently using GridListTileBar, which generates a DOM structure like this for its title property. <div class="MuiGridListTileBar-title-29" data-reactid=".0.3.0.$3 ...

Tips for inserting characters at the cursor in a contenteditable element?

Is there a way to simulate typing a character in either JQuery or plain JavaScript? I am working with a contenteditable section where I need to intercept user input to replace certain characters (such as straight quotes with curly ones). While I have foun ...

dyld: Unable to locate symbol: _node_module_register

Embarking on my Angular2 learning journey with the help of this GitHub repository: https://github.com/angular/quickstart After running npm install, I attempted to launch the project in a browser using npm start. However, I encountered the following error: ...