Attempting to insert into mongodb through javascript and html - javascript

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>

Related

How do would I create a cloud varible (High score) for a game

<script>
// I want to create a cloud variable (high score)
// But I don't know how.
var click = 0;
document.getElementById("High_score").innerHTML = cloud_varible;
function btn(){
click ++;
document.getElementById("p").innerHTML = click;
}
if (clicks < cloud_varible){
clicks = cloud_varible
document.getElementById("High_score").innerHTML = cloud_varible;
}
</script>
<button id="btn" onclick="btn();">click</button>
<p id="p">clicks: </p>
<p id="High_score"></p>
I've looked at various wbsite but none seem to awnser my qestion.
I have intermediate-basic knoledge in javascript. Intermediate-Advance HTML and intermediate Knoledge in CSS and basic knowledge in PHP.
My take on a solution for this will need you to be a little familiar with Node. Just some basics
What we will be doing is creating a little bit of backend logic to store our score. When you talk about "The Cloud" what it really is is just a computer that is accessible from anywhere. We will use Node and Express (a common combo) to create a small API to read and write to a local JSON file that holds the players name as well as their score
First lets go over the back end structure
const express = require("express");
var fs = require("fs")
const cors = require('cors')
var bodyParser = require('body-parser')
Express: This makes the API and endpoint creation super quick and easy
FS: This lets us Read and Write to a local file
body-parser: This lets us read the incoming data from our HTML page
const app = express();
app.use(express.json())
app.use(cors())
app.use(bodyParser.urlencoded({extended: false}));
Above are setting up express to use all of the middleware that we want
now lets take a look at the endpoints of our small API, we will have 2 endpoints. One to update the score and one to get the current highscore.
to update the score we will use a POST endpoint
app.post("/updateScore",(req,res) =>{
console.log(req.body)
obj = {
highscore:req.body.highscore,
playerName:req.body.playerName
}
fs.writeFile("score.json",JSON.stringify(obj),() =>{
console.log("writing file")
})
})
In this POST endpoint we take in the some values in the form of a json object. This object contains the players name and their score. we then write the resulting score and name to a json file. This file is saved on to the servers local storage so that it is accessible for reading
next up is the GET endpoint
app.get("/score", (req,res) => {
console.log()
fs.readFile("./score.json","utf-8",(err,data)=>{
console.log("ReadingFile")
parsedData = JSON.parse(data)
console.log(parsedData)
res.json(parsedData)
})
})
The GET endpoint Reads the contents of the json file on the server and then sends back the relevant information (in this case the score and name)
finally we will start the server on port 3000
app.listen("3000", () => {
console.log(`Server listening on 3000`);
});
That is all the information we need on the backend. Now we can work on the frontend page that will displayed to your users.
We need 2 functions on thet frontend side, the first will retreive the current score that is stored on the server. The second will update the score that is stored on the server. I have acomplished them as follows
function getHighScore(){
fetch("http://localhost:3000/score")
.then((res)=>{
return(res.json())
})
.then((res) => {
console.log(res)
document.getElementById("highScore").innerText = res.playerName + ": " + res.highscore
return(res)
})
}
The function above makes a GET request to the endpoint we setup earlier. it then takes the response form this endpoint and updates our HTML accordingly
function setHighScore(name, score){
fetch("http://localhost:3000/updateScore",{
method: "POST",
headers: {
'Content-Type': 'application/json'
},
body:JSON.stringify({
playerName: name,
highscore: score
})
})
.then(()=>{
console.log("Here")
getHighScore()
})
}
The function above makes a POST request to our endpoint form before. This time it supply's the server with relevant information to update the stored score accordingly. It is important to note that after we update the highscore on theserver we want to display this score as well, you will notice we call the getHighScore() function at the end of our promise as well to do so.
The last step is to put it all together in the HTML document. The full document looks as follows
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Gift</title>
<link rel="stylesheet" href="index.css">
</head>
<body>
<div id="main">
<div>
High Score:
</div>
<div id="highScore">
0
</div>
<div>
<button onclick="setHighScore('Josh',5)">Set New Score</button>
</div>
</div>
<script>
function getHighScore(){
fetch("http://localhost:3000/score")
.then((res)=>{
return(res.json())
})
.then((res) => {
console.log(res)
document.getElementById("highScore").innerText = res.playerName + ": " + res.highscore
return(res)
})
}
function setHighScore(name, score){
fetch("http://localhost:3000/updateScore",{
method: "POST",
headers: {
'Content-Type': 'application/json'
},
body:JSON.stringify({
playerName: name,
highscore: score
})
})
.then(()=>{
console.log("Here")
getHighScore()
})
}
getHighScore()
</script>
</body>
</html>

Retrieving the Transaction value from Georli Network using Web3 and JavaScript

I am trying to retrieve the transaction value from the Goerli network using the transaction number. This script used to work with the Rinkerby network. But when I try to make it work on the Goerli network, it does not work. I am interested in retrieving the data/value stored for this transaction.
I am trying to retrieve the data from this transaction address:
https://goerli.etherscan.io/tx/0xc4c9be69899f8e15eb0c1623cd7a362290bd647e0467d9d7af7578a9d8979bfd
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/web3#latest/dist/web3.min.js"></script>
<script>
//solution from here: https://codeforgeek.com/configure-infura-with-web3-and-node-js/
//const ethNetwork = 'https://rinkeby.infura.io/v3/e90e21a0290f452386b3efa1dc8df355';
const ethNetwork = 'https://goerli.etherscan.io/tx/';
const web3 = new Web3(new Web3.providers.HttpProvider(ethNetwork));
// let's fetch a balance
var acc = '0x244eabef05acf009746ce91fe1712daf3857e620';
web3.eth.getBalance(acc, async (err, result) => {
if (err) {
console.log(err);
return;
}
let balance = web3.utils.fromWei(result, "ether");
console.log(balance + " ETH");
});
var TNnum = '0xc4c9be69899f8e15eb0c1623cd7a362290bd647e0467d9d7af7578a9d8979bfd';
var trans = await web3.eth.getTransaction(TNnum);
console.log(trans)
var input = web3.utils.toAscii(trans.input)
console.log('input:' + input)
}
</script>
</head>
<body>
<h2>JavaScript Functions</h2>
<p>This example calls a function which performs a calculation, and returns the result:</p>
<p id="demo"></p>
<input type="button" value="GetData" id="myCheck" onclick="getData()">
</body>
</html>
I tried the attached code.

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>

Updating javascript variable on html page through html button click?

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>

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