Form keeps reseting even though there are errors why? [closed]

So I have provided two code that takes the value from users through html form process using vanilla js for front and node js for backend. so when I add existing value rather than showing errors in the span err blocks it keeps resetting the form. anybody please help.

I want my code to show the server errors in the error field in the html span blocks, but I an getting a form reset rather than showing error.

Front end code

document.addEventListener('DOMContentLoaded', () => {
  document.getElementById('signup-form').addEventListener('submit', async function submit(event) {
    event.preventDefault();
    // Clear previous error messages
    const errorFields = ['usernameerr', 'emailerr', 'passworderr', 'confirmPassworderr', 'fileerr'];
    errorFields.forEach(field => document.getElementById(field).textContent = '');

    const username = document.getElementById('username').value;
    const email = document.getElementById('email').value;
    const password = document.getElementById('password').value;
    const confirmPassword = document.getElementById('confirm-password').value;
    const file = document.getElementById('file').files[0];

    // Validate password
    if (password !== confirmPassword) {
      document.getElementById('confirmPassworderr').textContent = 'Passwords do not match';
      return;
    }

    const formData = new FormData();
    formData.append('username', username);
    formData.append('email', email);
    formData.append('password', password);
    formData.append('json', file);

    try {
      const response = await fetch('http://localhost:3000/signup', {
        method: 'POST',
        body: formData,
      });

      const result = await response.json();
      console.log('Server response:', result);

      if (response.ok) {
        alert(result.message);
        document.getElementById('signup-form').reset();
      } else {
        // Handle errors from the server
        if (result.user) {
          document.getElementById('usernameerr').textContent = result.user;
        }
        if (result.email) {
          document.getElementById('emailerr').textContent = result.email;
        }
        if (result.fileerr) {
          document.getElementById('fileerr').textContent = result.fileerr;
        }
      }
    } catch (error) {
      console.error('Error during submission:', error);
      alert('An error occurred. Please try again.');
    }
  });
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" rel="stylesheet">

<div class="signup-container">
  <form class="signup-form" id="signup-form">
    <h2>SignUp Form</h2>
    <div class="input-group">
      <label for="username"><i class="fas fa-user"></i></label>
      <input type="text" id="username" placeholder="Enter Username" required>
      <span id="usernameerr" class="error"></span>
    </div>
    <div class="input-group">
      <label for="email"><i class="fas fa-envelope"></i></label>
      <input type="email" id="email" placeholder="Enter Email" required>
      <span id="emailerr" class="error"></span>
    </div>
    <div class="input-group">
      <label for="password"><i class="fas fa-lock"></i></label>
      <input type="password" id="password" placeholder="Create Password" required>
      <span id="passworderr" class="error"></span>
    </div>
    <div class="input-group">
      <label for="confirm-password"><i class="fas fa-lock"></i></label>
      <input type="password" id="confirm-password" placeholder="Retype Password" required>
      <span id="confirmPassworderr" class="error"></span>
    </div>
    <div class="input-group">
      <label for="file"><i class="fas fa-file"></i></label>
      <input type="file" id="file" required>
      <span id="fileerr" class="error"></span>
    </div>
    <div class="reset">
      <a class="back" href="login.html" target="_blank">Already have an account?</a>
    </div>
    <button type="submit">SignUp</button>
  </form>
</div>

Backend code

const mysql = require('mysql2');
const express = require('express');
const cors = require('cors');
const fs = require('fs');
const multer = require('multer');
const path = require('path');
const app = express();

app.use(cors({
    origin: 'http://127.0.0.1:5500', // Replace with your frontend's origin
    methods: ['POST'],
    allowedHeaders: ['Content-Type']
}));

const con = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'password',
    database: 'signup'
});

con.connect(function (err) {
    if (err) {
        throw err;
    }
    console.log("Connected successfully");
});

const upload = multer({
    dest: "upload"
});

app.post('/signup', upload.single('json'), (req, res) => {
    const { username, email, password } = req.body;
    const file = req.file;

    if (!file) {
        return res.status(400).json({ fileerr: 'No file uploaded or incorrect format.' });
    }

    // Check for existing username or email
    const checkQuery = 'SELECT * FROM gui WHERE username = ? OR email = ?';
    con.query(checkQuery, [username, email], (err, result) => {
        if (err) return res.status(500).json({ error: 'Database query error' });

        if (result.length > 0) {
            const existing = result[0];
            if (existing.username === username) {
                return res.status(400).json({ user: 'Username already exists' });
            }
            if (existing.email === email) {
                return res.status(400).json({ email: 'Email already exists' });
            }
        }

        try {
            const fileData = fs.readFileSync(file.path, 'utf-8'); // Synchronous read
            const parsedData = JSON.parse(fileData); // Parse JSON to ensure validity

            // Insert data into the database
            const insertQuery = 'INSERT INTO gui(email, username, password, data) VALUES (?, ?, ?, ?)';
            con.query(insertQuery, [email, username, password, JSON.stringify(parsedData)], (err) => {
                if (err) return res.status(500).json({ error: 'Failed to insert data' });

                return res.status(201).json({ message: 'Signup successful' });
            });
        } catch (error) {
            return res.status(400).json({ error: 'Invalid JSON file or error reading the file' });
        }
    });
});

app.listen(3000, () => {
    console.log('listening on port 3000');
});

New contributor

itsspyner is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

5

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa

Form keeps reseting even though there are errors why? [closed]

So I have provided two code that takes the value from users through html form process using vanilla js for front and node js for backend. so when I add existing value rather than showing errors in the span err blocks it keeps resetting the form. anybody please help.

I want my code to show the server errors in the error field in the html span blocks, but I an getting a form reset rather than showing error.

Front end code

document.addEventListener('DOMContentLoaded', () => {
  document.getElementById('signup-form').addEventListener('submit', async function submit(event) {
    event.preventDefault();
    // Clear previous error messages
    const errorFields = ['usernameerr', 'emailerr', 'passworderr', 'confirmPassworderr', 'fileerr'];
    errorFields.forEach(field => document.getElementById(field).textContent = '');

    const username = document.getElementById('username').value;
    const email = document.getElementById('email').value;
    const password = document.getElementById('password').value;
    const confirmPassword = document.getElementById('confirm-password').value;
    const file = document.getElementById('file').files[0];

    // Validate password
    if (password !== confirmPassword) {
      document.getElementById('confirmPassworderr').textContent = 'Passwords do not match';
      return;
    }

    const formData = new FormData();
    formData.append('username', username);
    formData.append('email', email);
    formData.append('password', password);
    formData.append('json', file);

    try {
      const response = await fetch('http://localhost:3000/signup', {
        method: 'POST',
        body: formData,
      });

      const result = await response.json();
      console.log('Server response:', result);

      if (response.ok) {
        alert(result.message);
        document.getElementById('signup-form').reset();
      } else {
        // Handle errors from the server
        if (result.user) {
          document.getElementById('usernameerr').textContent = result.user;
        }
        if (result.email) {
          document.getElementById('emailerr').textContent = result.email;
        }
        if (result.fileerr) {
          document.getElementById('fileerr').textContent = result.fileerr;
        }
      }
    } catch (error) {
      console.error('Error during submission:', error);
      alert('An error occurred. Please try again.');
    }
  });
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" rel="stylesheet">

<div class="signup-container">
  <form class="signup-form" id="signup-form">
    <h2>SignUp Form</h2>
    <div class="input-group">
      <label for="username"><i class="fas fa-user"></i></label>
      <input type="text" id="username" placeholder="Enter Username" required>
      <span id="usernameerr" class="error"></span>
    </div>
    <div class="input-group">
      <label for="email"><i class="fas fa-envelope"></i></label>
      <input type="email" id="email" placeholder="Enter Email" required>
      <span id="emailerr" class="error"></span>
    </div>
    <div class="input-group">
      <label for="password"><i class="fas fa-lock"></i></label>
      <input type="password" id="password" placeholder="Create Password" required>
      <span id="passworderr" class="error"></span>
    </div>
    <div class="input-group">
      <label for="confirm-password"><i class="fas fa-lock"></i></label>
      <input type="password" id="confirm-password" placeholder="Retype Password" required>
      <span id="confirmPassworderr" class="error"></span>
    </div>
    <div class="input-group">
      <label for="file"><i class="fas fa-file"></i></label>
      <input type="file" id="file" required>
      <span id="fileerr" class="error"></span>
    </div>
    <div class="reset">
      <a class="back" href="login.html" target="_blank">Already have an account?</a>
    </div>
    <button type="submit">SignUp</button>
  </form>
</div>

Backend code

const mysql = require('mysql2');
const express = require('express');
const cors = require('cors');
const fs = require('fs');
const multer = require('multer');
const path = require('path');
const app = express();

app.use(cors({
    origin: 'http://127.0.0.1:5500', // Replace with your frontend's origin
    methods: ['POST'],
    allowedHeaders: ['Content-Type']
}));

const con = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'password',
    database: 'signup'
});

con.connect(function (err) {
    if (err) {
        throw err;
    }
    console.log("Connected successfully");
});

const upload = multer({
    dest: "upload"
});

app.post('/signup', upload.single('json'), (req, res) => {
    const { username, email, password } = req.body;
    const file = req.file;

    if (!file) {
        return res.status(400).json({ fileerr: 'No file uploaded or incorrect format.' });
    }

    // Check for existing username or email
    const checkQuery = 'SELECT * FROM gui WHERE username = ? OR email = ?';
    con.query(checkQuery, [username, email], (err, result) => {
        if (err) return res.status(500).json({ error: 'Database query error' });

        if (result.length > 0) {
            const existing = result[0];
            if (existing.username === username) {
                return res.status(400).json({ user: 'Username already exists' });
            }
            if (existing.email === email) {
                return res.status(400).json({ email: 'Email already exists' });
            }
        }

        try {
            const fileData = fs.readFileSync(file.path, 'utf-8'); // Synchronous read
            const parsedData = JSON.parse(fileData); // Parse JSON to ensure validity

            // Insert data into the database
            const insertQuery = 'INSERT INTO gui(email, username, password, data) VALUES (?, ?, ?, ?)';
            con.query(insertQuery, [email, username, password, JSON.stringify(parsedData)], (err) => {
                if (err) return res.status(500).json({ error: 'Failed to insert data' });

                return res.status(201).json({ message: 'Signup successful' });
            });
        } catch (error) {
            return res.status(400).json({ error: 'Invalid JSON file or error reading the file' });
        }
    });
});

app.listen(3000, () => {
    console.log('listening on port 3000');
});

New contributor

itsspyner is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

5

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật