How to save data from html form to a database using javascript

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.




  
  
  


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 command 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 sharing a simple example here today that explains how easily you can save your form data in a text file or in a .txt file using JavaScript.

A web form usually has many different elements, mostly input fields. You can extract data from these elements and save it in a database like SQL Server, or simply convert it into a JSON file. You can even save your form data in a text file.

Let’s see the example first.




    Save form Data in a Text File using JavaScript
    


    
id="selCountry">
id="msg" name="msg" placeholder="Write some message ..." style="height:100px">
onclick="saveFile()" />

Try it

Please do not get overwhelmed by the size of the program. The code inside the

Next, I am creating a Link (the anchor tag) (which is not visible anywhere on the form) and assigning the text file as the link’s download property.

let newLink = document.createElement("a");
newLink.download = sFileName;

Once I have created the link, I’ll assign the BLOB object as the href (or as the URL) to the newly created Link tag.

if (window.webkitURL != null) {
    newLink.href = window.webkitURL.createObjectURL(textToBLOB);
}
else {
    newLink.href = window.URL.createObjectURL(textToBLOB);
    newLink.style.display = "none";
    document.body.appendChild(newLink);
}

👉 Now, you can also convert your Form data into PDF using JavaScript.

How to save data from html form to a database using javascript

BLOB stands for Binary Large Object. BLOBs are typically, images and audio files, which are converted into Binary and are later stored in a database. Using the Blob() constructor, I can convert ordinary texts into Blob objects.

You can see the BLOB value (attached to the link’s URL or tag that we created in our script) in your browser’s console window. For example,

if (window.webkitURL != null) {
    newLink.href = window.webkitURL.createObjectURL(textToBLOB);
    console.log (newLink);    
}

image

How to save data from html form to a database using javascript

The image shows the tag with URL having the blob value. In the console window, copy the URL and paste it in the browser’s address bar. The browser will translate the BLOB and will show the value.

Remember: Every time you click the save button, the script will create a new BLOB from the form data.

The final line of code, simply calls the click event of the tag and the browser downloads the file containing the data in your local hard disc.

newLink.click();

👉 Not just plain text, you can even convert an image into a PDF using only JavaScript. Check out this post.

That's it. Thanks for reading.

← PreviousNext →


How do you insert data to database using JavaScript with HTML?

Create a js file named "insert" in DBexample folder and put the following data into it: var mysql = require('mysql'); var con = mysql. createConnection({.
var mysql = require('mysql');.
var con = mysql. ... .
host: "localhost",.
user: "root",.
password: "12345",.
database: "javatpoint".

How do you store data in database from HTML form using node JS?

How to Insert/Save Data from Html Form to Database in Node.js Express.
Step 1 – Create New Node Js Application..
Step 2 – Create Table in Database..
Step 3 – Install Express EJS, Session, Body Parser, Flash..
Step 4 – Create Route..
Step 5 – Connect App to Database..
Step 6 – Import Dependencies in App.js..

Can we store data in database using JavaScript?

JavaScript allows us to store data in the browser using local storage API. Here, you can use LocalStorage and SessionStorage . The objects let us store data (in key/value pairs) and update it from the browser's storage.

How can store form data in JavaScript?

if you want to save it on a database. submit the form to a page that can run some back-end code, like php, asp, coldfision, jsp, or what ever you favorite language is. NOTE: a more modern way of storing data is using Window. localStorage.