Updating javascript variable on html page through html button click? - javascript

I'm making a basic program where the user is shown a current room temperature along with a text field and "Set" button so that they can set their desired room temperature. What I want to happen is when the user enters a number into the text field and hits the Set button it changes the "roomTemp" variable to their desired temperature also known as "desiredTemp" and displays it as the current temperature. I don't think it's reaching the save() function as nothing is printed in my console when the button is clicked when it should output "Temperature is changing!" to my console.
Javascript File:
var http = require('http');
var ejs = require('ejs');
var fs = require('fs');
var roomTemp = 20;
var desiredTemp = 0;
http.createServer(function(req,res) {
res.writeHead(200, {'Content-Type': 'text/html'});
//since we are in a request handler function
//we're using readFile instead of readFileSync
fs.readFile('index.html', 'utf-8', function(err, content) {
if (err) {
res.end('error occurred');
return;
}
var renderedHtml = ejs.render(content, {roomTemp: roomTemp}); //get redered HTML code
res.end(renderedHtml);
});
}).listen(3000, "127.0.0.1");
console.log('Server Running at http://127.0.0.1:3000 CNTL-C to quit');
HTML File:
<!DOCTYPE html>
<html>
<head>
<script src="Thermostat.js"></script>
</head>
<body>
Current Temp: <%= roomTemp %> <br></br>
<form>
Desired Room Temperature: <input type="number" id="desTemp" name="roomTempDes"><br></br>
<button onclick="save(document.getElementById("roomTempDes").value)">Set</button>
</form>
<script>
function save(desiredTemp) {
roomTemp = desiredTemp;
console.log("Temperature is changing!");
}
</script>
</body>
</html>

You have too many quotation marks in your script.
"save(document.getElementById("roomTempDes").value)"
should be
"save(document.getElementById('roomTempDes').value)"

Your code is quoted incorrectly AND you have the WRONG ID.
<button onclick="save(document.getElementById('desTemp').value)">Set</button>

Related

Nodejs is not fully functional when running on autostart

I am currently trying to change the volume of my Raspberry Pi with two html buttons (volume up and volume down), using nodeJS. The volume change is done by calling a bash script when clicking on one of the html-buttons in index.html.
When I start node manually from terminal with
node server.js
everything works fine and I can increase and decrease the volume using the two buttons.
As soon as I put the node script to autostart, only the "volume up" button is working, while the volume down does not seem to be working.
Killing the autostarted node process and starting it manually, it works just fine again.
How can the outcome be this different, depending on how node is started here?
What is my error in this?
My node script looks like this:
var express = require('express');
var path = require('path');
var open = require('open');
var fs = require('fs');
const { exec } = require('child_process');
var bodyParser = require('body-parser');
var port = 3000;
var app = express();
app.get('/', function(req, res){
res.sendFile(path.join(__dirname, 'index.html'));
});
app.use(bodyParser.urlencoded({ extended: false }));
app.post('/', function(request, respond) {
var inputValue = request.body.volume;
if (inputValue == "up") {
exec('sh volumeup.sh');
}
if(inputValue == "down") {
exec('sh volumedown.sh');
}
});
app.listen(port, function(err){
if(err){
console.log(err);
}else{
open('http://localhost:' + port);
}
});
with my index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
</head>
<body>
<h2>Change Volume</h2>
<form action="" method="post">
<button name="volume" value="up">Volume Up</button>
<button name="volume" value="down">Volume Down</button>
</form>
</body>
</html>
To get the nodejs to run on autostart, I have set up a *.desktop-file:
[Desktop Entry]
Encoding=UTF-8
Type=Application
Name=<Node>
Comment=
Exec=/usr/bin/node /home/pi/Desktop/server.js
StartupNotify=false
Terminal=true
Hidden=false
Thank you very much in advance, I really appreciate your help!
Figured it out by myself.
In case anyone is facing a similar issue:
What helped me, was to put both shell file names into their absolute path:
´´´
app.post('/', function(request, respond) {
var inputValue = request.body.volume;
if (inputValue == "up") {
exec('sh /home/pi/server/volumeup.sh');
}
if(inputValue == "down") {
exec('sh /home/pi/server/volumedown.sh');
}
});
´´´
Bothered me for longer than I want to admit :-)

How can I make an HTML page that edits variables in a .JSON file?

Basically I have a .json file, and I want to make a html page that someone can fill out a form, and the information in the form will change variables in the JSON file.
Example:
The json file (for example):
{“title”: “(variable)”}
then when the html form is submitted it will read (variable) as what was entered into the form.
It depends on what you have on the backend (Node, python, etc)
Welcome to Stackoverflow, seeing that you have NodeJS, you may want to establish some sort of communication from your back end to front end. Let's say you're using websockets. Here is how information would be passed:
userData.json:
{
name: "Mishra",
age: 89
}
server.js:
const app = express()
const server = app.listen(3000) // setup express server
const io = require('socket.io').listen(server); // using websockets
let userData = require('./userData.json');
// on socket connection event
io.on('connection', (socket) => {
socket.on('updateName', name => { // when updateName is called
userData.name = name // set JSON var to new name
})
}
// method to save JSON file goes here
myForm.html:
<head>
<script type="text/javascript" src="your/path/to/socket.io.js"></script>
<script>
var socket = io();
</script>
</head>
<body>
Set name:
<input type="text" id="nameField" name="fname"><br>
<input type="submit" value="Submit" id="submit">
<script>
document.getElementById("submit").onclick = () =>{
socket.emit("updateName", document.getElementById("nameField").value)
}
</script>
</body>

Update part of HTML page using NODE.JS and EJS

I have the following express app which just renders the sample.ejs page. On that page when I press the button the attached script changes the div text to
"THIS IS FROM J QUERY. I want the same thing to happen but I want the data to be coming from a database. In my express app if I try to use res.render(); every time I click the button then it reloads the page which I don't want. So is there a way to achieve this without reloading page and only update part of page?
I have searched stack overflow and the web but can't get an appropriate answer or maybe I just am unable to understand. I know this is a very basic thing to ask.
APP.js
var express = require('express');
var app = express();
app.use(express.static('public'));
app.use(express.static('./src/views'));
app.set('views', './src/views');
app.set('view engine' , 'ejs');
app.listen(3000 , (err)=>{console.log('Listening')});
app.get('/' , function(req , res) {
res.render('sample' , {result_from_database: res.body} );
});
sample.ejs
<!doctype html>
<html lang="en">
<head>
<title>Sample HTML File</title>
</head>
<body>
<div id="holder">
WELCOME
</div>
<form>
<button type="button" id="HButton"> HELLO </button>
</form>
</body>
<script>
$(document).ready(function () {
var form = $("#holder");
$("#HButton").on("click", function () {
form.html("THIS IS FROM J QUERY");
});
});
</script>
<script src="/lib/jquery/dist/jquery.js"></script>
</html>
Now this is what I want to do
<!doctype html>
<html lang="en">
<head>
<title>Sample HTML File</title>
</head>
<body>
<div id="holder">
<%= result_from_database %>
</div>
<form>
<button type="button" id="HButton"> HELLO </button>
</form>
</body>
<script>
$(document).ready(function () {
var my_div = $("#holder");
$("#HButton").on("click", function () {
/* Tell app.js that I clicked a button and then app.js
query the database and using ejs or something else update the
my_div inner html with the database result without
reloading page */
});
});
</script>
<script src="/lib/jquery/dist/jquery.js"></script>
</html>
NOTE: I'm not asking how to query the database
-Thanks
You have to define and endpoint in your back end that return the information you want to display:
app.js
var express = require('express');
var app = express();
app.use(express.static('public'));
app.use(express.static('./src/views'));
app.set('views', './src/views');
app.set('view engine' , 'ejs');
app.listen(3000 , (err)=>{console.log('Listening')});
app.get('/' , function(req , res) {
res.render('sample' , {result_from_database: res.body} );
});
app.get('/api/books', function(req, res) {
res.json({
message: 'Your database information'
});
});
then on your front end you need to make a call to api endpoint like:
sample.ejs
<script>
$(document).ready(function () {
var my_div = $("#holder");
$("#HButton").on("click", function () {
$.ajax({
url: "/api/books"
})
.done(function( data ) {
console.log( "Sample of data:", data );
$('#holder').html(data.message);
});
});
});
</script>
You can find more information on ajax call with jquery here.
However i would suggest you to use any framework like angular or react to make it easier to render the data in your html, otherwise you will have to write a lot of code using jquery.

Attempting to insert into mongodb through javascript and html

I'm fairly new to mongodb, node and the like, I was trying to perform a simple task of inserting a blogpost into my database that I already created, what I decided to do is to make a web page with a button, once clicked, would then insert into my mongo database, but unfortunately I've been failing to do so. I know to insert I must use the terminal, for example node server.js and then it'll insert, however I want that to occur by just pressing the button on the html page. So any advice on what to do will be appreciated, the following is my current code.
<!DOCTYPE html>
<html>
<head>
Add Blog Post
</head>
<body>
<h1>
Welcome to your Blog! Feel free to add a blog post!
</h1>
<form>
Title: <br>
<input type = "text" name = "Title" id = "title"><br>
Blog Post: <br>
<input type = "text" name ="EnterBlog" id = "blog"> <br>
<input type = "button" value = "Submit Blog" onclick="
var insertDocuments = function(db, callback) {
// Get the documents collection
var collection = db.collection('blog');
var title = Title.value;
var blog = EnterBlog.value;
// Insert some documents
collection.insertMany([
{Title: title}, {Blog : blog}
], function(err, result) {
assert.equal(err, null);
assert.equal(2, result.result.n);
assert.equal(2, result.ops.length);
console.log('Inserted 2 documents into the Blog collection');
callback(result);
});
}
exports.insertDocuments = insertDocuments;
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
// Connection URL
var url = 'mongodb://localhost:27017/blogapp';
// Use connect method to connect to the Server
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log('Connected correctly to server');
insertDocuments(db, function() {
db.close();
});
});"
>
</form>
</body>
</html>

Why don't my Javascript prompts show up from my Express.IO .ejs file?

I am relatively new to JavaScript and subsequently Node + Express.IO. I am trying to build a page that will track in real time connections made by different 'users' to the server. Consequently, when I do include all the functions from the io module, my prompt() and alert do not work anymore. I am running nodemon app.js from my terminal and no compilation errors are showing up when I do so. The alert and prompt work again when I remove all the io functions.
These are the contents of my index.ejs <body> tag:
<body>
<h1>Chatroom</h1>
<script>
alert("Hello!");
var name = prompt("What is your name?");
io.connect();
io.emit.('got_a_new_user', {name: name});
io.on('new_user', function(data) {
//render this new info in the HTML
var users = data.users;
console.log(users);
if (users != undefined) {
console.log("\n\n\n" + users);
// if users is defined, append the new division containing the username
}
});
io.on('disconnect_user', function(data) {
var users = data.users;
if (users != undefined) {
// If users is defined remove the corresponding HTML element
}
});
</script>
<div id="container">
</div>
</body>
Any help would be much appreciated.
Adding example for the comment added by UKatz,
You will have to connect socket.io from the client as follows,
index.ejs
<script src="http://ip:port/socket.io/socket.io.js"></script>
<script type="text/javascript">
var socket = io.connect('http://ip:port');
socket.emit('got_a_new_user', {name: name});
</script>
Check socket.io documentation for how to connect socket.io with client.

Categories