How do you save data from an html form to a mysql database using javascript? - Stack Overflow

I am trying to save data from an html form into a mysql database. Obviously I am new to this so I know

I am trying to save data from an html form into a mysql database. Obviously I am new to this so I know I am doing something wrong but after doing a lot of research I still can't figure it out. I created a simple version of my form for testing purposes.

<!DOCTYPE html>
<html>

  </head>
  <body>
  <script src="scripts/test.js"></script>


<form>
<input id="firstName" type="text" class="form-control" name="firstName" placeholder="First Name">
 <input id="lastName" type="text" class="form-control" name="lastName" placeholder="Last Name">
 <input id="userName" type="text" class="form-control" name="userName" placeholder="Username">
 <input id="inputText" type="text" class="form-control" name="email" placeholder="Email">
<input id="currentPassword" type="password" class="form-control" name="currentPassword" placeholder="Current Password"> 

 <input type="submit" onclick="saveAccount()" id="createAccountButton" class="button2" value="Create Account"></input>

</form>

  </body>
</html>

My javascript code is:

function saveAccount(){
var mysql = require('mysql');

var con = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "abc123",
  database: "PBSC_Parking_DB"
});

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

var firstName = document.getElementById("firstName");
var lastName = document.getElementById("lastName");
var psw = document.getElementById("psw");
var userName = document.getElementById("userName");
var email = document.getElementById("inputText");



var sql = "INSERT INTO accounts (UserName, FirstName, LastName, Email, UserPassword) VALUES ('"+userName+ "', '"+firstName+"','"+lastName+"','"+email+"','"+psw+"')";
con.query(sql, function (err, result) {
    if (err) {
        throw err;

    }

    console.log(result.affectedRows + " record(s) updated");
  });
}

I've read that you're suppose connect to the database outside of a function but moving it outside the function does not seem to solve my problem. I've also been told that I shouldn't be using 'document.' but I'm not sure how else to pull the data from the form to be used in my sql statement.

I tried hard coding values into an INSERT statement, not using a function and just running the js file through the mand prompt. This works to update my database so I know I'm doing the connection correctly... I just don't know how to make it work with the form.

note: I also tried looking up tutorials using nodejs and ejs but after following the tutorials carefully I still couldn't get them to work.

I am trying to save data from an html form into a mysql database. Obviously I am new to this so I know I am doing something wrong but after doing a lot of research I still can't figure it out. I created a simple version of my form for testing purposes.

<!DOCTYPE html>
<html>

  </head>
  <body>
  <script src="scripts/test.js"></script>


<form>
<input id="firstName" type="text" class="form-control" name="firstName" placeholder="First Name">
 <input id="lastName" type="text" class="form-control" name="lastName" placeholder="Last Name">
 <input id="userName" type="text" class="form-control" name="userName" placeholder="Username">
 <input id="inputText" type="text" class="form-control" name="email" placeholder="Email">
<input id="currentPassword" type="password" class="form-control" name="currentPassword" placeholder="Current Password"> 

 <input type="submit" onclick="saveAccount()" id="createAccountButton" class="button2" value="Create Account"></input>

</form>

  </body>
</html>

My javascript code is:

function saveAccount(){
var mysql = require('mysql');

var con = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "abc123",
  database: "PBSC_Parking_DB"
});

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

var firstName = document.getElementById("firstName");
var lastName = document.getElementById("lastName");
var psw = document.getElementById("psw");
var userName = document.getElementById("userName");
var email = document.getElementById("inputText");



var sql = "INSERT INTO accounts (UserName, FirstName, LastName, Email, UserPassword) VALUES ('"+userName+ "', '"+firstName+"','"+lastName+"','"+email+"','"+psw+"')";
con.query(sql, function (err, result) {
    if (err) {
        throw err;

    }

    console.log(result.affectedRows + " record(s) updated");
  });
}

I've read that you're suppose connect to the database outside of a function but moving it outside the function does not seem to solve my problem. I've also been told that I shouldn't be using 'document.' but I'm not sure how else to pull the data from the form to be used in my sql statement.

I tried hard coding values into an INSERT statement, not using a function and just running the js file through the mand prompt. This works to update my database so I know I'm doing the connection correctly... I just don't know how to make it work with the form.

note: I also tried looking up tutorials using nodejs and ejs but after following the tutorials carefully I still couldn't get them to work.

Share Improve this question asked Apr 21, 2020 at 4:04 Alexandra AmaraAlexandra Amara 11 gold badge1 silver badge4 bronze badges 3
  • the var mysql = require('mysql'); means this code is meant for a node.js server-side context. It seems like you are trying to run it "cient-side" aka in a browser. You need to get a node.js server and create http endpoints as you might have with express.js. – WillD Commented Apr 21, 2020 at 4:07
  • I already have nodejs installed. If you have any resources on how to 'create http endpoints'/how i would use them I would appreciate it.. I can't find many good resources on how to save the form data. – Alexandra Amara Commented Apr 21, 2020 at 4:13
  • expressjs./en/starter/hello-world.html start here and create some routes on your node server. One of these routes should be something like /save-form-data then you can "hit" this route either with the action attribute of the <form> or using an AJAX call from your client side JS. Make the callback for this route the node script that saves the row to your database. – WillD Commented Apr 21, 2020 at 4:23
Add a ment  | 

2 Answers 2

Reset to default 2

This popped up for me when I had this exact question and couldn't really figure out the answer without scrounging the internet and trial and error.

const http = require('http');
const fs = require('fs');
const url = require('url');
const { Client } = require('pg');
const querystring = require('querystring');

const server = http.createServer((req, res) => {
  const parsedUrl = url.parse(req.url, true);
  const pathname = parsedUrl.pathname;

  if (req.method === 'GET' && pathname === '/') {
    fs.readFile(__dirname + '/index.html', (err, data) => {
      if (err) {
        res.writeHead(500, { 'Content-Type': 'text/plain' });
        res.end('Internal Server Error');
      } else {
        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.end(data);
      }
    });
  } else if (req.method === 'POST' && pathname === '/submitForm') {
    let body = '';
    req.on('data', (chunk) => {
      body += chunk.toString();
    });

    req.on('end', () => {
      const { username, firstName, lastName, email, password } = querystring.parse(body);

      const client = new Client({
        host: 'localhost',
        port: 3030,
        user: 'user',
        password: 'password',
        database: 'database',
      });

      client.connect((err) => {
        if (err) {
          console.error('Error connecting to the database:', err);
          res.writeHead(500, { 'Content-Type': 'text/plain' });
          res.end('Internal Server Error');
          return;
        }

        const sql = `INSERT INTO users (UserName, FirstName, LastName, Email, UserPassword) 
                     VALUES ($1, $2, $3, $4, $5)`;
        const values = [username, firstName, lastName, email, password];

        client.query(sql, values, (err, result) => {
          if (err) {
            console.error('Error executing SQL query:', err);
            res.writeHead(500, { 'Content-Type': 'text/plain' });
            res.end('Internal Server Error');
          } else {
            res.writeHead(200, { 'Content-Type': 'text/plain' });
            res.end('Form submitted successfully');
          }

          client.end();
        });
      });
    });
  } else {
    res.writeHead(404, { 'Content-Type': 'text/plain' });
    res.end('Not Found');
  }
});

const port = 3000;
server.listen(port, () => {
  console.log(`Server running at port ${port}`);
});

don't forget to install the necessary packages and replace the client section. But to explain the code : We're using Node.js's built-in http module to create a simple HTTP server.

We're handling GET and POST requests based on the URL path (pathname) and HTTP method.

For GET requests to '/', we're serving the 'index.html' file.

For POST requests to '/submitForm', we're parsing the request body to get form data and inserting it into the database.

There are much better ways to do this using express.js but with just pure js this is what I could e up with. Also, remend this https://developer.mozilla/en-US/docs/Learn/Forms it will help more things click

You are just retrieving the DOM elements from the form. What you want to query are the values of the inputs.

var firstName = document.getElementById("firstName").value;

And the same for the other variables.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745534727a4631853.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信