How to display data from MySQL into HTML-Page with NodeJS - javascript

I'm new in Node JS and I'm trying to display the fetched data from my MySQL Table into a table in my HTML-File. But I couldn't find anything that helped me. I would really appreciate it if somebody can help me to get a solution! :)
Here's my js-code:
//app.js
// Get the mysql service
var mysql = require('mysql');
var express = require('express');
var app = express();
app.get('/', function (request , response) {
fetchData(response);
console.log('Done. Displayed Data.');
});
// Add the credentials to access your database
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'Breunninger',
port: '3306'
});
// connect to mysql
connection.connect(function(err) {
if(err){throw err;}
console.log('Connected');
});
function executeQuery(sql, cb){
connection.query(sql, function( result, fields){
cb(result);
})
}
function fetchData(response){
executeQuery("SELECT username, tor, datum, sendungsstruktur FROM Buchung JOIN user ON(user.id = Buchung.userid)", function (result) {
console.log(result);
response.write('<div class="container-wrap"><table id="example" class="display"><tr>');
for(var column in result[0]){
response.write('<td> <label>' + column + '</label></td>');
response.write('</tr>');
}
for(var row in result){
response.write('<tr>');
for(var column in result[row]){
response.write('<td>' + result[row][column]+ '</td>');
}
response.write('</tr>');
}
response.end('</table></div>');
});
}
<div class="container-wrap">
<div class="flexslider">
<script src="app.js"></script>
</div>
</div>

There's a small (but critical!) error in the executeQuery function, the first argument should be the error object, so if you can re-write this as below your query should work.
function executeQuery(sql, cb){
connection.query(sql, function( error, result, fields){
if (error) {
console.error("An error has occurred:", error);
} else {
cb(result);
}
})
}
Node callback usually reserve the first argument for an error object, it's easy to miss this!
Also, we should be clear, the Node.js Express code will be running on the server side, so to see the results you need to point your browser to the host and port this is serving, e.g. http://localhost:3000/ (if you do:)
app.listen(3000);

Related

Getting a 404/405 error while making a post request from front end AJAX to a given route in node Js. The localhost URL doesn't work

I want to load data from database as soon as page loads at front end, therefore I specified the route as '/' in GET. I am able to get the records in the console but my page doesn't load at http://127.0.0.1:3000. Here is a snap of the way I am creating server through node:
Yes I actually ran my server side through node app.js before creating this server
Moreover, even if it opens, and when I try to make a POST request to '/details' route, I get http 405 error. Here is a snap of my index.html where I am making an AJAX request:
In other ways, if I specify route as '/' in node Js and then make a request to '/', it inserts the record the way I want to.
I am quite new to AJAX and node Js. Can someone tell me where am I going wrong?
Here is my entire server side code:
const fetchOptions = {
headers: {
'Content-Type': 'application/json'
},
mode: 'cors'
};
var http=require("http");
var mysql=require("mysql");
var express=require('express');
var fs=require('fs');
var bodyParser=require('body-parser');
var app=express();
app.use(express.static('public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
console.log('Creating the http server');
var con= mysql.createConnection({
host: "localhost",
user: "root",
password: "root",
database: "budget_mgmt"
});
con.connect(function(err){
if(err)
{
console.log('Error connecting to db');
return;
}
console.log('Connection established');
});
var statement= "select * FROM budget_mgmt.item_description";
app.get('/',function(request,response)
{
fs.readFile('index.html',function(err,data)
{
console.log("The home page: index.html");
});
con.query(statement,function(error,results, fields)
{
if(error) throw error;
console.log(results);
response.end(JSON.stringify(results));
}); //response.end(data);
});
app.post('/details',function(request,response)
{
console.log(request.body);
console.log(request.body.description);
console.log(request.body.category);
console.log(request.body.amount);
console.log(request.body.date);
var sql = "INSERT INTO item_description(description,category,amount,today) VALUES ('"
+request.body.description+"','"+request.body.category+"',"+request.body.amount+","+"date_format(str_to_date('"+request.body.date+
"','%m-%d-%Y'),'%Y-%m-%d'));";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted");
});
http.createServer(app).listen(3000,"127.0.0.1");

Passing Object with module exports

I am still new to nodejs and Javascript, I am sorry if my question appear to be very simple but I am struggling a lot and I can't seem to find an answer on the net.
What I want to do is basically calling a script (sqlRequest.js) and send an integer while calling it. This script will send an sql request to my database and will return the result (an object) to the original file.
Here are the codes:
router.post('/request', function(req, res, next){
var id = req.body.id;
var essai = require('./sqlRequest.js');
console.log("INDEX: "+essai.sendSQL(id)); });
And now the sqlRequest.js code:
exports.sendSQL = function(id) {
var mysql= require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'bcombes',
password : 'bertrand1994',
database : 'totalkpi'
});
connection.connect();
var sql ="SELECT * FROM tra_ticket where id=?";
var insert=[id];
sql=mysql.format(sql, insert);
connection.query(sql, function(err, rows, fields) {
if (err) {
console.log('Error while performing Query.');
connection.end();
}
else {
connection.end();
console.log(rows);
return rows;
}
});};
On the console I can see that the console.log("INDEX: "+essai.sendSQL(id)); appears to be undefined and is displayed before the console.log(rows).
Is it possible that the server does not wait for the function to finish and display the variable anyway ?
Anyway thank you for taking the time to help.
Your logic to pass a variable between files is fine. The reason your seeing essai.sendSQL(id) return undefined is because connection.query(...) is called asynchronously and, as you've mentioned in your question, the console.log fires before the DB query completes.
To fix that issue you just need to refactor your code slightly:
var essai = require('./sqlRequest.js');
router.post('/request', function(req, res, next){
var id = req.body.id;
// send callback to sendSQL
essai.sendSQL(id, function(index) {
// this will only fire once the callback has been called
console.log("INDEX: " + index)
})
});
And then in sqlRequest.js:
exports.sendSQL = function (id, cb) {
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
user: 'bcombes',
password: 'bertrand1994',
database: 'totalkpi'
});
connection.connect();
var sql = "SELECT * FROM tra_ticket where id=?";
var insert = [id];
sql = mysql.format(sql, insert);
connection.query(sql, function (err, rows, fields) {
if (err) {
console.log('Error while performing Query.');
connection.end();
}
else {
connection.end();
console.log(rows);
// call the callback
cb(rows);
}
});
};

trying to fetch specific data from mysql using node.js

i am new to node.js and my boss has entrusted me with a job to integrate a notification system in our attendance project..
so far i have successfully created a connection to my data base using express and mysql node modules
and the code that helped me in achieving that is given below
var express=require('express');
var mysql=require('mysql');
var app=express();
var connection=mysql.createConnection({
host:'localhost',
user:'root',
password:'',
database:'attendance'
});
connection.connect(function(error) {
if(!!error) {
console.log('Error in connection');
} else {
console.log('Connected');
}
});
app.get('/',function (req, resp) {
connection.query("Select * from employee_leaves", function (error, rows, fields) {
if (!!error) {
console.log("Error in the query");
} else {
console.log("successfully done\n");
console.log(rows);
}
});
})
app.listen(1337);
// now the issue is i want to query this statement
SELECT * from employee_leaves WHERE employee_leave_company_name ='$sup_company_name' AND leave_status='Pending'ORDER BY employee_leave_id desc"
the issue is these variable $sup_company_name is in php so
1) how should i fetch value from that variable
2)how to use where clause in node.js
Note:: $sup_company_name is declared in my require.php file
the code of require.php file is given below P.S i m accessing that variable in my other pages by include('require.php') but i dont know how to access that variable in node.js
session_start();
$sup_id = $_SESSION['employee_id'];
$sup_type=$_SESSION['employee_type'];
$sup_company_name=$_SESSION['employee_company_name'];

How can i pipe mysql data to a browser window instead of the console in Nodejs?

Hi I am currently trying to output mysql data to a browser window instead of the console, and I have not a clue on how to do this in Node, which I am quite new to.
Here is the mysql.js file:
'
var mysql = require ("mysql");
var connection = mysql.createConnection({
host:"localhost",
user: "root",
});
connection.connect(function (err) {console.log( "Successfully Connected.");
if (err) throw err;
});
var query = connection.query("SELECT * FROM myTable", function (err, result, fields){
if (err) throw err;
console.log('result:', result);
});
connection.end();'
You need to create a server which you can connect to and receive data from with a browser. The most convenient and by far the simplest way to do this is HTTP. You can read about HTTP servers in node.js here. The fist code snippet on that page demonstrates a HTTP server with one handler function, which is all you need to achieve your goal.
An (untested) example for convenience:
// Dependencies
var mysql = require("mysql"),
http = require("http");
// This holds our query results
var results;
// Connect to database
var connection = mysql.createConnection({
host: "localhost",
user: "root"
});
connection.connect(function(err) {
if (err) throw err;
console.log("Connected to database");
});
connection.query("SELECT * FROM myTable", function(err, rows, fields) {
if (err) throw err;
results = rows;
connection.end(); // Disconnect from database
});
// Function to handle browser's requests
function requestHandler(req, res) {
res.end(JSON.stringify(results)); // Respond to request with a string
}
// Create a server
var server = http.createServer(requestHandler);
// That magic number 8080 over here is the port our server listens to.
// You can access this webpage by visiting address http://localhost:8080
server.listen(8080, function() {
console.log("Server online");
});

node.js + MySQL & JSON-result - Callback-issue & no response to client

I'd like to use node.js to query a mySQL-database and return the results as JSON to be used in a mobile application. Unfortunately, my request just sorta times out and the server does nothing for a good 2 minutes until the log-files show my console.log()-statements.
Also, the callback doesn't return anything as result. It's just empty.
// Check dependencies
var http = require('http');
// Create the http server.
// reference: http://net.tutsplus.com/tutorials/javascript-ajax/node-js-for-beginners/
http.createServer(function(request, response) {
// Attach listener on end event.
request.on('close', function() {
console.log('request');
// run asynchronous
getSQL(function(err, result) {
console.log('json:', result);
response.writeHead(200, {
'Content-Type' : 'x-application/json'
});
// Send data as JSON string.
response.end(result);
});
});
}).listen(3000);
// Access MySQL via node-mysql
// https://github.com/felixge/node-mysql
function getSQL(callback) {
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'user',
password : 'pw',
database : 'db',
socketPath : '/var/run/mysqld/mysqld.sock', // socket for communication from debian <-> client, seems not to be set correcly by default?
});
connection.connect();
var json = '';
var query = 'SELECT * FROM test';
connection.query(query, function(err, results, fields) {
if (err)
return callback(err, null);
console.log('The result is: ', results[0]);
// wrap result-set as json
json = JSON.stringify(results);
});
connection.end();
callback(null, json);
};
Output after like 2 minutes:
$ node app.js
request
json:
The result is: { test: 'avc' }
json2: [{"test":"avc"}]
Based on my very basic understanding of the whole node.js-concept, my code should query the db (it does) and return a json once it's finished via the callback-function (apparently doesn't) which than is sent back as a response to the client (can't really check that since the json's empty).
I guess I made one (or a couple) major mistakes. Help and/or helpful links would be much appreciated. Thanks!
Solution, thanks to hexacyanide
// Check dependencies
var http = require('http');
// Create the http server.
// reference: http://net.tutsplus.com/tutorials/javascript-ajax/node-js-for-beginners/
/***************
* Correction 1: Using the request.on('close', function()( ... )-listener isn't required anymore
***************/
http.createServer(function(req, res) {
console.log('Receving request...');
var callback = function(err, result) {
res.writeHead(200, {
'Content-Type' : 'x-application/json'
});
console.log('json:', result);
res.end(result);
};
getSQL(callback);
}).listen(3000);
// Access MySQL via node-mysql
// https://github.com/felixge/node-mysql
function getSQL(callback) {
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'user',
password : 'pw',
database : 'db',
socketPath : '/var/run/mysqld/mysqld.sock', // socket for communication from debian <-> client, seems not to be set correcly by default?
});
connection.connect();
var json = '';
var query = 'SELECT * FROM test';
connection.query(query, function(err, results, fields) {
if (err)
return callback(err, null);
console.log('The query-result is: ', results[0]);
// wrap result-set as json
json = JSON.stringify(results);
/***************
* Correction 2: Nest the callback correctly!
***************/
connection.end();
console.log('JSON-result:', json);
callback(null, json);
});
};
You're following an older guide which instructs you to wait for the request's close event before sending the response, but you actually no longer need to do that.
What's happening is you aren't sending your response, so your client is timing out. Only until the client times out is when close events fires. Since the client has disconnected by the time you send your response, you don't get anything on the client and only see it in the terminal.
To fix this problem, just stop waiting for the close event and run code immediately when the request handler is called:
var http = require('http');
http.createServer(function(req, res) {
getSQL(function(err, result) {
res.writeHead(200, {
'Content-Type' : 'x-application/json'
});
res.end(result);
});
}).listen(3000);

Categories

Resources