I have been practicing with a simple html form to mysql using nodejs, but it doesnt seem to work, the html is called index.html and my nodejs file is called test.js, here is my code:
My html
<!DOCTYPE html>
<html>
<head>
<title>email test form</title>
</head>
<body>
<form method="post" action="/data">
<label for="email">Voer je email in </label> <input type="email"
name="email"></input>
<input type="submit" value="submit">
</form>
<script src="test.js"></script>
</body>
</html>\
My javascript for node js:
var express = require('express');
var app = express();
var mysql = require('mysql');
var bodyParser = require ('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static('public'));
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "Bionicle123!",
database: "account"
});
con.connect(function(err){
if (err) throw err;
console.log("Je bent verbonden aan de database!");
});
app.post("/data", function(req, res) {
var userEmail = req.body.email;
console.log(userEmail);
var sql = "INSERT INTO persoon (email) VALUES (?)";
con.query(sql, userEmail, function (err, data) {
if (err) {
console.log("Failed ah mattie!");
} else {
console.log("Gelukt ah mattie!");
}
});
});
Uncaught ReferenceError: require is not defined at test.js:1
You've tagged this question node.js.
You need to run your JavaScript using Node.js.
Download it from https://nodejs.org/en/ , then install it, then run node test.js.
Not allowed to load local resource: file:///C:/newuser
You need to load your HTML document from the webserver that you write using Node.js. Otherwise the action URL won't point to the right place.
… but first you need to finish writing the web server. Look at the Hello World example for Express.js (which you are also using).
You need to call listen. That will give you a URL you are point the browser to.
Related
(Please correct my terminology if it's not correct.)
My files server.js, run.js and index.html, are in the same directory.
server.js
Sets up the server.
const express = require('express');
const path = require('path');
const run = require('./run.js');
var app = express();
app.get('/index.html', function(req, res){
res.sendFile(path.join(__dirname + '/index.html'));
});
app.get('/', function(req, res){
res.redirect('index.html');
});
app.post('/run', async function(req, res){
var data = await run.run();
res.json(data);
});
app.listen(5000, function () {
console.log('Dev app listening on port 5000');
});
run.js
Will contain functions that consumes time. Here just one function as example:
async function run(){
//do time consuming stuff
var data = {
"status" : "ok",
"a1" : 1,
"a2" : 2
};
return data;
}
module.exports = {
run:run
}
index.html
Simple form.
<!DOCTYPE html>
<html>
<body>
<form id="search-form" action="/run" method="post">
Input:<br>
<input type="text" name="input1" id="input1" value = ""> <br>
<input type="submit" value = "Run">
</form>
<script></script>
<div id="data"></div>
</body>
</html>
When I run the server, go to localhost:5000 in the browser, and click the run button, I get redirected to a page just showing the content of data.
What I would like to happen when I click the the run button is;
The server process /run post request
A response is sent with res.json or res.send to the client
A javascript script on the client side should catch the response, process it, and make some change to the html code (in my case, create some table).
How can I achieve this?
So your problem is that you're using a form. Forms will redirect you to the specified web page with all of the form's data.
You need an XMLHttpRequest.
var xhr = new XMLHttpRequest();
xhr.open("POST", "/run", true);
xhr.send();
If you ever need the data of your form to be submitted as well, I have some documentation on how to do that.
Hope this helps!
I'm new to Node.js and JavaScript. I have a specific problem but mostly need advice on the best solution.
I'm running a Node server. I want the client to be able to submit a string to the server, then the server to display a new HTML page that shows the string data.
I'm using Express and Socket.io.
In the following files, the client sees index.html, then after submitting the form it sees return.html. I print the input string to the console, and the output is as expected (whatever the user enters). But the return.html is never updated with the input string.
I also tried sending the return.html page and the change_result call in an async series, but the sendFile function never ends and the second function in the series is never called. In previous attempts it worked intermittently with a setTimeout around the emit('change_result') function.
Why doesn't the call to change_result do anything? I used the same technique to update the headings of the original index.html in previous versions. Should I be routing to localhost.../return.html and sending the post data there, or something like that?
server.js
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var bodyParser = require('body-parser') //for POST request
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
server.listen(8080, function() {
console.log("Server running on port 8080.");
});
var dir = __dirname;
app.get('/', function(req, res) {
res.sendFile(dir + '/index.html');
});
app.post('/', function(req, res) {
var query1=req.body.input1
console.log("Server: In post request.")
console.log(query1);
res.sendFile(dir + '/return.html');
io.emit('change_result', {
result: query1
});
});
index.html
<!DOCTYPE html>
<html>
<body id="body">
<form method="post" action="http://localhost:8080">
String: <input type="text" name="input1" id="input1" />
<input type="submit" id="button1" value="Submit" />
</form>
</body>
</html>
return.html
<!DOCTYPE html>
<html>
<body id="body">
<p id="heading1">Result: </p>
<script>
document.addEventListener('DOMContentLoaded', function() {
var socket = io();
socket.on('change_result', function(data) {
document.getElementById('heading1').innerHTML = "Result: \""+data.result"\"";
});
});
</script>
</body>
</html>
I'm not knee-deep inside socket.io, but IMO the problem is, that the server has no way to know if any listeners are ready.
I think you should emit a 'ready' event, once the return.html is loaded, then listen to 'change_result'. Also separate the socket communication from the POST response on the server. Like so.
server.js
var query;
app.get('/', function(req, res) {
res.sendFile(dir + '/index.html');
});
app.post('/', function(req, res) {
query = req.body.input1;
console.log("Server: In post request.");
console.log(query);
res.sendFile(dir + '/return.html');
});
io.on('connection', function(socket) {
socket.on('ready', function() {
socket.emit('change_result', {result: query});
});
});
return.html
<script>
document.addEventListener('DOMContentLoaded', function() {
var socket = io();
socket.emit('ready', function(data) {});
socket.on('change_result', function(data) {
document.getElementById('heading1').innerHTML = "Result: \""+data.result + "\"";
});
});
</script>
so I've created this application that allows me to call a phone number from my Twilio account through localhost. I just have to put a / after the port # and the phone number I want to call(localhost:2222/7786453738) and it will send out a call. but I want the user to be able to make that call by inputting a phone number on to the webpage then clicking a button. is that possible? here's my code so far in the index.js file. I run it by going node index.js in the command terminal.
const express = require("express");
const app = express();
const port = 2222;
app.get("/", function(req, resp){
resp.end("welcome to my app");
});
app.get("/:data", function(req, resp){
var accountSid = 'accountSid'
var authToken = 'authtoken'
var client = require('twilio')(accountSid, authToken);
client.calls.create({
url: 'https://demo.twilio.com/welcome/voice/',
to: req.params.data,
from: '6043302056',
}, function(err, call) {
if(err) {
console.log(err);
} else {
console.log(call.sid);
}
})
console.log(req.params.data);
if(req.params.data == "me"){
resp.end("hi raj");
//resp.sendFile(__dirname+"/public/index.html)
} else {
resp.end("Now calling: "+req.params.data);
}
});
app.listen(port, function(err){
if(err){
console.log("error starting "+err);
return false;
}
console.log("port is running. "+port);
})
Twilio developer evangelist here.
You're most of the way there with what you want to achieve. You can absolutely create a form that will take an input from a user and dial the number they enter.
First up, You will want to update your route as the number you send through a form won't be a part of the path, instead it will come as part of the body of the request. In order to read request bodies in express, you will want the body-parser module. So, install that in your project with:
npm install body-parser --save
Then include it in your file and use it with your app:
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
Now, form's usually POST their data, rather than working over GET, so let's update your route to receive that POST request and extract the number from the request:
app.post("/calls", function(req, resp) {
const accountSid = 'accountSid'
const authToken = 'authtoken'
const client = require('twilio')(accountSid, authToken);
const number = req.body.number;
client.calls.create({
url: 'https://demo.twilio.com/welcome/voice/',
to: number,
from: '6043302056',
}, function(err, call) {
if(err) {
console.error(err);
} else {
console.log(call.sid);
}
})
console.log(number);
if(req.params.data == "me"){
resp.end("hi raj");
//resp.sendFile(__dirname+"/public/index.html)
} else {
resp.end("Now calling: " + number);
}
});
Now, you need an HTML file that will include a form to make the request to this endpoint. Create an HTML file called index.html and place it in a new folder in your application called public.
You can load static files from the public directory in express with this line, add it near the top, after you create the app:
const path = require('path');
app.use('/static', express.static(path.join(__dirname, 'public')));
Finally we just need the HTML. This is the simplest HTML I could write that would do what you need:
<!DOCTYPE html>
<html>
<head>
<title>Make a call</title>
</head>
<body>
<form action="/" method="POST">
<label for="number">What number do you want to call?</label>
<input id="number" type="tel" />
<button type="submit">Make call</button>
</form>
</body>
</html>
As you can see it is just a form with a single input, the number, and a button to submit it.
Give this all a go and let me know how you get on.
Yes,
first: you can do that, but you need to write the code in HTML File or at least include this code in html file, and call the Twilo's function after you click on the respective button. For that first, render a HTML page, after user enters the address, on that HTML Page give input number and call now button feature. and after user clicks on the button, do:
function callNow() {
var num = document.getElementById('number').value;
client.calls.create({
url: 'https://demo.twilio.com/welcome/voice/',
to: num,
from: '6043302056',
}, function(err, call) {
if(err) {
console.log(err);
} else {
console.log(call.sid);
}
{
Your HTML Code should be:
<input id="number">
<button onclick="callNow()">Call Now</button>
You can include twilio cdn and use this feature. I am just giving you the concept, I hope you will find this helpful.
i am trying to insert some data to database using node and mysql i manage to get it done, but after query response the browser loads continuously i tried pooling still nothing happens
Here is my code
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false })
var sql = require('mysql');
var pool = sql.createPool({
host : 'localhost',
user : 'root',
password : '',
port : '3306',
database : 'node'
});
app.get('/nodeThis', function (req, res) {
res.sendFile(__dirname + '/insert.html');
});
app.post('/nodeThis', urlencodedParser, function (req, res) {
var post={user_name:req.body.name1,user_what:req.body.what,user_why:req.body.why};
pool.getConnection(function(err, connection){
connection.query('INSERT INTO user SET ?', post, function(err){
if(err){
console.log(err);
}else{
console.log('succes');
}
});
connection.release();
});
});
server.listen(3000);
Here is how i pass the data from HTML to node
<html>
<body>
<div>
<form action="/nodeThis" method="post">
<input type="text" name="name1">
<input type="text" name="what">
<input type="text" name="why">
<button class="boom">Submit</button>
</form>
</div>
</body>
</html>
After the database operation, you aren't sending any response to the browser; you just sent an output to the console instead; the browser was waiting for a response that never came
If you insert res.sendFile(__dirname + '/insert.html'); or some other response after the console.log('succes');, you'll see an output on the browser.
That being said, I hope this is just a proof of concept and not a production code.
Update Based on the Comment
Retrieving the number of rows affected
After running the executing the database insertion function
db.query("insert into table", [data-to-insert], function(err, result){
//to retrieve the number of rows affected
var number_of_rows = result.affectedRows
})
the result has a property called affectedRows that allows the user to know how many rows were inserted, updated, or deleted.
To retrieve the primary id of the inserted row (if it has one), result has a property called insertId.
var id = result.insertId
Hope this helps!
I'm trying to get form data to node server using POST method.
This is my HTML code,
<html>
<head>
<title>
Node Architecture
</title>
</head>
<body>
<h1>Node Architecture</h1>
<h3>Enter Your name.</h3>
<form action="/" method="POST">
<input type="text" name="eventname" />
<input type="submit" value="Go" />
</form>
</body>
</html>
This is my node app, index.js
var app = require('express')();
var http = require('http').Server(app);
//var io = require('socket.io')(http);
//var qs = require('querystring');
app.get('/', function(req, res){
res.sendfile('index.html');
});
app.get('/events', function(req, res){
res.sendfile('events.html');
});
app.get('/movie', function(req, res){
res.sendfile('movie.html');
});
app.post('/', function(req, res) {
var name = req.body.eventname;
console.log(name);
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
Now when I click submit I get an error message which is as follows,
TypeError: Cannot read property 'eventname' of undefined at Object.handle
How do I print the entered name to my console?
Express doesn't parse request body by default, you will have to use a middleware to do that.
Try this.
var express = require('express');
var app = express()
.use(express.bodyParser());
...
...
Also, you should read this article. It explains some of the problems (and their solutions) related to common body parsing approach.
Add these lines into your app.js.
require body-parser.
var bodyParser = require('body-parser');
put before your first app.get that will be better.
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
good luck.