0

Script

This my Javascript script at the bottom within the HTML file:

var savedValues = []
var currentId = document.getElementById("fridgeFreezer").value

function handleChange() {
// The new values for the fridge with id currentId:
var temp = document.getElementById("temperature").value
var comments = document.getElementById("comments").value

// Save these values for the previous id
// - First, check to see if we already have a record we can update
var save = savedValues.find(save => {
  return save.id === currentId
})
// - If we do, update it, otherwise create a new record
if (save) {
  save.temp = temp
  save.comments = comments
} else {
  savedValues.push({
    id: currentId,
    temp: temp,
    comments: comments,
  })
}

// Update the current id to the newly selected option
currentId = document.getElementById("fridgeFreezer").value

This is the output on console in Google Chrome

{…}]
0: {id: "Fridge 1", temp: "", comments: ""}
1: {id: "Fridge 2", temp: "3", comments: "a"}
length: 2
__proto__: Array(0)

Node JS

I have a controller

exports.getData = async function(req, res) {
  var {savedValues} = req.body;
  console.log(savedValues);
}

Details

This currently doesn't do anything.

Question

How can I get any variable from JavaScript script and use it in Node JS?

Goal:

I am aiming to get values from JavaScript script to use in Node JS to insert into MySQL database.

Full HTML Code

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
    <link rel="stylesheet" href="/style.css">
  </head>
  <body>

    <nav>
      <h4>Technical</h4>
      <ul>
        <li><a href="/">Home</a></li>
          {{#if user}}
          <li><a href="/profile">Profile</a></li>
          <li><a href="/auth/logout">Logout</a></li>


        {{else}}
          <li><a href="/login">Login</a></li>
          <li><a href="/Register">Register</a></li>
        {{/if}}
      </ul>
    </nav>

    <div class="container mt-4">
      <h1 class="text-left" style="margin-bottom: 50px">Daily Fridge & Freezer Monitoring Record</h1>
        <form action="/auth/21-TEMP-01b" method="post">
          <div class="form-group">
            <label>Select Fridge Or Freezer</label>
            <select class="form-control" id="fridgeFreezer" name="fridge">
              <option value="Fridge 1">Fridge 1</option>
              <option value="Fridge 2">Fridge 2</option>
              <option value="Fridge 3">Fridge 3</option>
              <option value="Fridge 4">Fridge 4</option>
              <option value="Fridge 5">Fridge 5</option>
              <option value="Fridge 6">Fridge 6</option>
              <option value="Fridge 7">Fridge 7</option>
              <option value="Fridge 8">Fridge 8</option>
              <option value="Fridge 9">Fridge 9</option>
              <option value="Fridge 10">Fridge 10</option>
              <option value="Freezer 1">Freezer 1</option>
              <option value="Freezer 2">Freezer 2</option>
              <option value="Freezer 3">Freezer 3</option>
              <option value="Freezer 4">Freezer 4</option>
              <option value="Freezer 5">Freezer 5</option>
            </select>
          </div>

          <div class="form-group">
            <label>Temperature °C</label>
            <input class="form-control" type="number" id="temperature" name="temperature">
          </div>

          <div class="form-group">
            <label>Comments</label>
            <textarea class="form-control" rows="3" id="comments" name="comments"></textarea>
          </div>

          <button type="submit" class="btn btn-primary">Submit</button>
        </form>



  <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
  <script type="text/javascript">

var savedValues = []
var currentId = document.getElementById("fridgeFreezer").value

function handleChange() {
// The new values for the fridge with id currentId:
var temp = document.getElementById("temperature").value
var comments = document.getElementById("comments").value

// Save these values for the previous id
// - First, check to see if we already have a record we can update
var save = savedValues.find(save => {
  return save.id === currentId
})
// - If we do, update it, otherwise create a new record
if (save) {
  save.temp = temp
  save.comments = comments
} else {
  savedValues.push({
    id: currentId,
    temp: temp,
    comments: comments,
  })
}

// Update the current id to the newly selected option
currentId = document.getElementById("fridgeFreezer").value

// Load any previously saved data for this new id
save = savedValues.find(save => {
  return save.id === currentId
})
// If we find a previous value, load it, otherwise empty the inputs
if (save) {
  document.getElementById("temperature").value = save.temp
  document.getElementById("comments").value = save.comments
} else {
  document.getElementById("temperature").value = ''
  document.getElementById("comments").value = ''
}

console.log(savedValues);

}

// Attach the event listener to the document
document.getElementById("fridgeFreezer").addEventListener('change', handleChange, false);


  </script>
  </body>
</html>

8
  • What ajax methods or libraries are you using? Commented Jul 14, 2020 at 13:48
  • If your elements are inside a form then you can use req.body using express Commented Jul 14, 2020 at 13:49
  • @Rod911 I am using express, handlebars as my view engine. Commented Jul 14, 2020 at 13:51
  • if you are intend to submit the form as form data, how about set a hidden value in your form, and el.value = JSON.stringify(savedValues); when form.onSubmit ? Another way is to add <input name="savedValues.0.comments" /> (0 is the index of the array). Or if you would like to submit it via js, take a look at developer.mozilla.org/en-US/docs/Web/API/XDomainRequest/send , or using jQuery is kind of easy way to do AJAX call. api.jquery.com/jquery.ajax Commented Jul 14, 2020 at 13:59
  • 1
    you mean you dont want ppl to manually edit the JSON object via console? so instead of keep generate savedValues and set it in <input type="hidden" />, you should do $('form').on('submit', function() { // set hidden value; return true; // continue to submit form }); to set that value right before form submission. Thats only one of the solutions, you can submit the object as jsonData via javascript using ajax too. stackoverflow.com/questions/4295782/… Commented Jul 14, 2020 at 15:52

1 Answer 1

1

You could simply make a route in your node.js and then when you submit the form you make a post call to the route from your javascript

const form = document.getElementById('user-form') //give your form an id
form.addEventListener('submit', submitform, false) //add event listener 
var submitform = function sbmform(e) {
  e.preventDefault() // prevent submission
  submitvalues() // exec function 
}
var savedValues = []

function submitvalues() {
  var currentId = document.getElementById("fridgeFreezer").value
  // The new values for the fridge with id currentId:
  var temp = document.getElementById("temperature").value
  var comments = document.getElementById("comments").value

  // Save these values for the previous id
  // - First, check to see if we already have a record we can update
  var save = savedValues.find(save => {
    return save.id === currentId
  })
  // - If we do, update it, otherwise create a new record
  if (save) {
    save.temp = temp
    save.comments = comments
  } else {
    savedValues.push({
      id: currentId,
      temp: temp,
      comments: comments,
    })
  }

  // Update the current id to the newly selected option
  currentId = document.getElementById("fridgeFreezer").value

  data = {
    data: savedValues
  }
  // make an call to submit the values 
  fetchobj = {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(data)
  }
  url = "your route url"
  fetch(url, fetchobj)
  form.removeEventListener('submit', submitform, false);
  form.submit()

}
Sign up to request clarification or add additional context in comments.

18 Comments

in your javascript in your html page
Below my current javascript script? p.s thanks for quick response
and what would i do in node js to receive it?
in the submitform(){} function in the answer add your code inside (the code that gets the values ....)and an api call to the a route in your node js
you could use the same route as the one in the form to receive the values or make one if you use express in your node just do somthing like app.post('\name-your-route',(req,res)=>{})
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.