Open In App

How to find email in database using Ajax ?

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn how to find an email in a database using Ajax. The jQuery ajax() method uses asynchronous HTTP requests to connect with the server. Here we will use a Node.js server and a MongoDB database.

Let’s understand using step-by-step implementation. 

Step 1: Create a folder named CHECKEMAIL and run the following command to start a Node.js application.

npm init -y

 

Step 2: Using the following command, install the required npm packages.

npm install express body-parser mongoose nodemon

Step 3: In your project directory, create a file named index.js.

Project Structure: Our project directory should now look like this.

 

Step 4: Require and configure the express app so that it may begin listening for requests. Our server is configured to use Port 3000.

index.js

Javascript




const express = require("express");
const bodyParser = require("body-parser");
const app = express();
  
app.use(express.json());
app.use(
bodyParser.urlencoded({
    extended: true})
);
  
app.listen(3000, () => {
    console.log("Server started on port 3000");
});


Step 5: Include the script below in the package.json file. This means that we can start our server using npm start, which will use the Nodemon package that we previously installed.

package.json

"scripts": {
     "start": "nodemon index.js"
},

Step 6: To start the server type the command npm start in the terminal.

 

Step 7: Require and connect to the MongoDB database using the mongoose package. If you’re working on a local project, the MongoDB server URL is probably mongodb:/localhost:27017/databaseName. The default port is 27017.

Javascript




const mongoose = require("mongoose");
mongoose
    .connect("mongodb://localhost:27017/mydb", {
        useNewUrlParser: true,
      })
      .then(() => {
        console.log("Database connected");
      })
      .catch((err) => {
        console.log("Connection failed");
      })


Step 8: Restart the server to see if the database is successfully connected or not.

 

Steps to find an email in a database using Ajax:

Step 1: Create an HTML file named index.html which contains an input field and submit button. When the user presses the submit button, it makes a POST request with JSON data to the / route on the server, and then the server gives an appropriate response.

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" 
        content="width=device-width, initial-scale=1.0" />
    <script src=
      </script>
</head>
  
<body>
    <h1 style="color: green">GeeksforGeeks</h1>
    <input type="text" placeholder="Email" 
        name="email" id="email" />
    <button id="btn">Submit</button>
    <div id="output" style="background-color: green; 
        color: #fff; width: fit-content">
      </div>
  
    <script>
        $(document).ready(() => {
            $("#btn").click(() => {
                $("#output").empty();
                let email = $("#email").val();
                $.ajax({
                    method: "POST",
                    url: "/",
                    data: { emailId: email },
                    success: function (data) {
                        
                        // Success callback function
                        if (data.length !== 0) {
                            $("#output").append(`<p>_id: 
                            ${data[0]._id}</p>`);
                            $("#output").append(`<p>email: 
                            ${data[0].email}</p>`);
                        } else {
                            $("#output").append(`<p>Not Found!</p>`);
                        }
                        console.log(data);
                    },
                    error: function (error) {
                        
                        // Error callback function
                        console.log(error);
                    },
                });
            });
        });
    </script>
</body>
  
</html>


Step 2: Create a get request to render the HTML file on our server.

Javascript




app.get("/", (req, res) => {
    res.sendFile(path.join(__dirname + "/index.html"));
});


Step 3: Make a Model to represent the structure of our database. We have a schema here that outlines our database structure. It has an email attribute.

Javascript




const userSchema = {
    email: {
        type: String,
        required: true,
      },
};
const user = mongoose.model("users", userSchema);


Step 4: Handle the post request using the model we just created. The email attribute is accepting the emailId from the request body.

Javascript




app.post("/", async (req, res) => {
    try {
        const userEmail = await user.find({
            email: req.body.emailId });
        res.send(userEmail);
      } catch (error) {
        console.log(error);
      }
});


Output:

 



Last Updated : 15 Nov, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads