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>
Eduards
  • 1,734
  • 2
  • 12
  • 37
  • What ajax methods or libraries are you using? – Rod911 Jul 14 '20 at 13:48
  • If your elements are inside a form then you can use req.body using express – saketh Jul 14 '20 at 13:49
  • @Rod911 I am using express, handlebars as my view engine. – Eduards Jul 14 '20 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 (0 is the index of the array). Or if you would like to submit it via js, take a look at https://developer.mozilla.org/en-US/docs/Web/API/XDomainRequest/send , or using jQuery is kind of easy way to do AJAX call. https://api.jquery.com/jquery.ajax/ – Allen Wong Jul 14 '20 at 13:59
  • @AllenWong If I hide it - the values are there to be edited within the console. – Eduards Jul 14 '20 at 15:13
  • I don't understand what you mean. Just set the value in `` right before form submit should be okay, you can keep the old code for editing the values after submission if you want. – Allen Wong Jul 14 '20 at 15:28
  • @AllenWong Let's say I inspect element and find that `hidden input` I can manually edit the `JSON` values within the console – Eduards Jul 14 '20 at 15:33
  • 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 ``, 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. https://stackoverflow.com/questions/4295782/how-to-process-post-data-in-node-js/4296402#4296402 – Allen Wong Jul 14 '20 at 15:52

1 Answers1

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()

}
Sven.hig
  • 4,449
  • 2
  • 8
  • 18
  • in your javascript in your html page – Sven.hig Jul 16 '20 at 14:49
  • Below my current javascript script? p.s thanks for quick response – Eduards Jul 16 '20 at 14:50
  • and what would i do in node js to receive it? – Eduards Jul 16 '20 at 14:53
  • 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 – Sven.hig Jul 16 '20 at 14:55
  • 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)=>{})` – Sven.hig Jul 16 '20 at 14:58
  • let me know if you need more help – Sven.hig Jul 16 '20 at 14:59
  • Have you got a youtube video or something I can learn in depth? – Eduards Jul 16 '20 at 15:00
  • nothing comes to mind at the moment but I am pretty sure there are plenty of good tutorials there – Sven.hig Jul 16 '20 at 15:02
  • do you know how to use node.js and make a route? – Sven.hig Jul 16 '20 at 15:03
  • Just at the basics - just trying to learn by creating something. I understand the `get` `post` methods and how to interact the form with node js – Eduards Jul 16 '20 at 15:04
  • from your javascript code I think you want to mimic updating values in the database, if that's what you want, then you should move your javascript code from front end (html) to backend node.js and handle the new values there – Sven.hig Jul 16 '20 at 15:07
  • I think I need a re-think to my structure. In terms of Front-End maybe instead of storing all data to 1 variable which at the moment it is:`savedValues`, I maybe should have multiple forms. This will make it easier for me to create functions such as `This form is not filled out - please fill all data`. – Eduards Jul 16 '20 at 15:11
  • I suggest you get this example working first and learn from it and then change it after this way you will learn about 2 different approaches and which one works better for you – Sven.hig Jul 16 '20 at 15:26
  • Very good point - I will see where I get to with this :D – Eduards Jul 16 '20 at 15:27
  • Saving the values in your front end is definitely not a good idea because you will be exposing your data and anyone can change it – Sven.hig Jul 16 '20 at 15:28
  • the code I added above will allow you to make your code work buy sending the values – Sven.hig Jul 16 '20 at 15:29
  • I have updated the code and added your js code in it and a fetch to your node route check it out – Sven.hig Jul 16 '20 at 15:56
  • problem with that code is - I cannot save values for each fridge from the dropdown – Eduards Jul 17 '20 at 06:08