browser display error after request node.js - javascript

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!

Related

Process form submit response from express server with javascript

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

Send new HTML page and make GET request to it after POST request from original page

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>

how can I make the client talk to the express server?

So I am trying to link this interface to a server so that the message I input in the front end is Posted in a separate webpage hosted on the server. eg "Hello [name]"
This is the interface:
<form id="loginformA" action="userlogin" method="post">
<div>
<label for="Insert message here">Message: </label>
<input type="text" id="message" name="message"></input>
</div>
and this is the server I am trying to post the message to:
var express = require('express');
var app = express();
app.use(express.static('public'));
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.post("/userlogin", function(request, response) {
response.send( "Hello " + request.body.message );
});
app.listen(process.env.PORT || 8080, process.env.IP);
I am just not sure how to make the interface and server talk to each other. I would also like to store all the messages in a db too, but that is for later after I figure this out.
Thanks!
Right now your form submits to /userlogin. You should define that route in your server like this:
app.post('/userlogin', function(req, res){
res.send('Hello' + req.body.message);
}
req.body is basically the post data submitted by your form, in this case only the input named 'message.'
any time you wish to submit a form to a node server, ensure the action corresponds to a route or method with an identical name.
From your html ...
app.post('/userlogin', function(request, response) {
response.send( "Welcome, your message is: " + request.body.message );
});

How to implement push notification system on a mysql database with node.js

I'm totally new to node.js and I want to implement push notification system on a MySql database. I have a notification table in my database. In this table I have store recipient_id that specify the recipient of the notification. Now I want when a new notification with recipient_id is equal to current logged in user's id notify that user. Something like Stackoverflow If you are in the for example java tagged questions, every time a new question with java tag create, a notification appear on top of the page : 1 question with new activity.
Sorry for my poor English. Please help me to implement this system, because I'm new to it.
I have made a simple app like your requirement.
You can get help from following lines of code.You need to understand the basics of code. after that you will easily achieve your target. most of things from your requirement covered in this demo app.
Its not a exact but you will meet your target through this.
In this example a status post by any user will emit to all other users also at same time. we can manipulate it to achieve "1 new status".
make a table in database where your entries to be saved
CREATE TABLE status
(
`status_id` INT NOT NULL AUTO_INCREMENT,
`s_text` TEXT,
`t_status` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY ( `status_id` )
);
//server.js
var app = require("express")();
var mysql = require("mysql");
var http = require('http').Server(app);
var io = require("socket.io")(http);
/* Creating POOL MySQL connection.*/
var pool = mysql.createPool({
connectionLimit: 100,
host: 'localhost',
user: 'root',
password: '',
database: 'fbstatus',
debug: false
});
app.get("/", function(req, res) {
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket) {
console.log("A user is connected");
socket.on('status added', function(status) {
add_status(status, function(res) {
if (res) {
io.emit('new status', status);
} else {
io.emit('error');
}
});
});
});
var add_status = function(status, callback) {
pool.getConnection(function(err, connection) {
if (err) {
connection.release();
callback(false);
return;
}
connection.query("INSERT INTO `status` (`s_text`) VALUES ('" + status + "')", function(err, rows) {
connection.release();
if (!err) {
callback(true);
}
});
connection.on('error', function(err) {
callback(false);
return;
});
});
}
http.listen(3000, function() {
console.log("Listening on 3000");
});
//index.html
<html>
<head>
<title>Socket.io</title>
<script src="/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<script src = "http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<script>
$(document).ready(function(){
var socket = io();
$("#add_status").click(function(){
socket.emit('status added',$("#comment").val());
});
socket.on('new status',function(msg){
var count = $('#count_status').text();
var valCount = parseInt(count);
if(valCount>=1) {
valCount = valCount+1;
} else {
valCount = 1;
}
var showMsg = '<div id="count_status"> '+valCount+' </div> new status';
$("#show_comments").html(showMsg);
});
});
</script>
</head>
<body>
<div id="comment_box" style = "padding:5%;">
<textarea id="comment" rows="5" cols="70"></textarea><br /><br />
<input type="button" id="add_status" value="Add">
</div>
<div id= "show_comments" class = "jumbotron"></div>
</body>
</html>
Run the app with following command
node Server.js
Now run http://localhost:3000/ in browser and to see the result open a new window in which you post a status and see your new status notification in both the window.
Thanks
Edited: This a great startup tutorial. a few thing needs modification.
connection.release() code ends up unreadable and not working. you should comets or remove it.
2.The actual output in my case:
You can do it 2 ways:
Query the server every n seconds for any new messages. Pass a timestamp of the last time you checked as a parameter and if any notification since the last check, return as json and display them in the client. This is called a pull strategy.
Or you can use websockets which maintains a permanent connection between your client and server, and then you can send notifications to the client from your server code in real-time. See socket.io tutorials. This is called a push strategy.

Displaying HTML in NodeJS

I need to display <img src="http://my.pic/test/rg/pict.png" /> from `items`.`img`
But when res.write(rows[0].img, 'utf8');,
I see in browser:
<img style="display: none !important;" src="http://my.pic/test/rg/pict.png" />
How do I fix style="display: none !important;"?
express = require('express'), app = express();
var mysql = require('mysql');
app.listen(8080);
mysql.connect = function(req, res, next){
var connect = mysql.createConnection({
host : 'localhost',
user : 'person',
password : 'ppasw',
database : 'db1'
});
return connect;
}
server.get(new RegExp('/img'), function(req, res, next){
var db =mysql.connect();
db.connect();
db.query("use `bd1`");
db.query("SELECT `img` FROM `items` WHERE `id`='" + intval(req.query.id) + "'",
function (err, rows, fields) {
res.setHeader("Content-Type", "text/html");
res.write(rows[0].img, 'utf8');
res.end();
});
db.end();
});
----*
I find problem - Adblock plugin.
Can you add this debug code before the res.write part ?
console.log(rows[0].img)
My best guess is that the style attribute is already in the database.
My second best guess is that you might have some javascript running in your browser which hides broken images.
Depending on the information on the database, you may have to construct the HTML. If you're only putting the URL to the image in there, it's not going to work right. You might have to do something like:
res.write('<html><body><img src="' + rows[0].img + '" /></body></html>');
If the database has all of the HTML already stored (I suggest not doing that) and you don't have any extensions hiding broken images, you're going to have to have some client side Javascript to unhide the image.

Categories