Home > Blockchain >  Express: When submitting the form returning a ? in the url
Express: When submitting the form returning a ? in the url

Time:10-04

When submitting a form returning a "?" in the URL When posting it redirects me to the page and returning a ? in the URL.

Directory: server.js, index.html, package.json, package-lock, src/models/form.js``

server.js:

const express = require("express");
const app = express();
const router = express.Router();

app.use(express.urlencoded());
app.use(express.json());
app.use("/", express.Router());
app.use(express.static(__dirname   "/src"));

const mongoose = require("mongoose");

mongoose.connect(
  "",
  {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  }
);
const db = mongoose.connection;
db.once("open", function () {
  console.log("Connected To MongoDB!");
});
db.on("error", console.error.bind(console, "Connection Error: "));

const PORT = process.env.PORT || 4000;

app.get('/', (req, res) => {
    res.sendFile(__dirname   '/index.html')
});

app.post("/login", async function (req, res) {
    alert("Nice")
//   const model = new formModel({
//     name: req.body.name,
//     age: req.body.age,
//     gender: req.body.gender,
//   });
//   res.redirect('/');

//   try {
//     await model.save();
//     res.send(model);
//   } catch (err) {
//     res.status(500).send(err);
//   }
});

app.get("/users", async (request, response) => {
  const users = await formModel.find({});

  try {
    response.send(users);
  } catch (error) {
    response.status(500).send(error);
  }
});


app.listen(PORT, () => console.log(`Running on ${PORT}`))

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">
    <title>Document</title>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP u1T9qYdvdihz0PPSiiqn/ /3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-skAcpIdS7UcVUC05LJ9Dxay8AXcDYfBJqt1CJ85S/CFujBsIzCIv l9liuYLaMQ/" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU" crossorigin="anonymous">
</head>
<body>

    <h1>Type anything you want</h1>

    <form>
        <label for="name">Username</label>
        <input type="text" id="name">
        <label for="age">Age</label>
        <input type="number" id="age">
        <label for="gender">Gender</label>
        <input type="text" id="gender">
        <button class="btn btn-dark" id="submit">Submit</button>
        </form>

            <script type="text/javascript">
        $(document).ready(function() {
            let username, age, gender;
            $("#former").submit(function() {
                username = $("#name").val();
                age = $("#age").val();
                gender = $("#gender").val();
                $.ajax({
                    url: '/login',
                    type: 'POST',
                    cache: false,
                    data: {
                        username: username,
                        age: age,
                        gender: gender
                    },
                    success: function(data) {
                        alert("Success!")
                    },
                    error: function(jqXHR, textStatus, err) {
                        alert('Text status: '   textStatus   ', err '   err)
                    }
                })
            })
        })
    </script>
</body>
</html>

It doesn't fire the alert function and when I'm saving a data to MongoDB it's not even saving it's just returning some ? in the URL

CodePudding user response:

When submitting a form with javascript, you must prevent the default behavior of the form by calling preventDefault() on the event.

https://api.jquery.com/submit/

("#former").submit(function(event) {
  event.preventDefault()
  // your code
  ...
}

CodePudding user response:

Nevermind! I just didn't add an attribute id to the form, so yea that's why.

  • Related