Home > Back-end >  How to post a a variable to node.js from Javascript--> MYSQL
How to post a a variable to node.js from Javascript--> MYSQL

Time:11-05

I can't seem to find a clean clear example of how to post/pass a variable from javascript to Node.js. I want to save what the user types in the text box and then pass that string in node js and then do whatever.

Client

<!DOCTYPE html>
<html>
<body>

<h2>HTML Forms</h2>

<form >
  <label for="fname">First name:</label><br>
  <input type="text" id="fname" name="fname" value="John"><br>
 

 
</form> 
<button onclick="hello()">Click me</button>

</body>
<script>

function hello () {
  var passed_variable = document.getElementById("fname");
  
  // THIS VARIABLE NEEDS TO GO TO NODE.JS
}
</script>
</html>

Node.js

const express = require("express");
const app = express();
var mysql = require('mysql');


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


con.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");
  var sql = "INSERT INTO files(email) VALUES (PASSED VARIABLE)";
  con.query(sql, function (err, result) {
    if (err) throw err;
    console.log("1 record inserted");
  });
});

app.listen(3000, () => {
  console.log("Application started and Listening on port 3000");
});

// serve your css as static
app.use(express.static(__dirname));

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

I want to take this variable and save into my localhost mysql db.

CodePudding user response:

You can use ?, as shown in the docs

var sql = "INSERT INTO files(email) VALUES (?)";
  con.query(sql, [someVar], function (err, result) {
    if (err) throw err;
    console.log("1 record inserted");
});

CodePudding user response:

On your node application, add a POST route: app.post('/sendData', (req, res)) => { console.log(req.body.yourFieldName) }. this will print any data on the field: yourFieldName sent to the route: http://localhost:3000/sendData.

on your client side application, you can use something like Axios, fetch or simple XHR to make a POST request in order to send the passed_variable to the above endpoint.

CodePudding user response:

You can use axios with cdn https://cdnjs.com/libraries/axios or

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

after this you can call axios.post()

const data = { passed_variable }
axios.post('https://example.com', data)

You can find the documentation here -> https://axios-http.com/docs/intro

  • Related