Angular, PieChart, NodeJS and multiple queries - sql

I'm trying set my second query to the pie chart datasource in angular and nodejs using multiple queries to get the results at same time
Someone have some idea to solve it.
Server Side
var url = require('url');
//Require express,
var express = require('express');
//and create an app
var app = express();
var mysql = require('mysql');
var connection = mysql.createConnection({
multipleStatements: true,
host: 'localhost',
user: 'hello',
password: 'passw',
database: 'db',
port: 330333
});
//var connection = mysql.createConnection({multipleStatements: true});
app.get('/home', function (req, res) {
res.send('Hello World!');
});
app.get('/sts', function (req, res) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Credentials", true);
res.header("Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept");
// res.header('Access-Control-Allow-Methods', 'POST, \n\
// GET, PUT, DELETE, OPTIONS');
connection.query(
" SELECT ST.manufacturer, ST.name, ST.model, ST.os, ST.status, " +
" SI.Coord, ST.Last_Update_Date_Time FROM " +
" ( " +
" select s.manufacturer, s.name, s.model, s.os, s. status, " +
" concat(DATE(s.last_update_date),' ',TIME(s.last_update_time)) as Last_Update_Date_Time " +
" from sts s " +
" order by Last_Update_Date_Time DESC " +
" ) AS ST JOIN " +
" ( " +
" select DISTINCT CONCAT(si.latitude, ', ', si.longitude) as Coord, " +
" concat(DATE(update_date),' ',TIME(update_time)) as Update_Date_Time " +
" from sts_info si " +
" order by Update_Date_Time DESC " +
" ) AS SI ON ST.Last_Update_Date_Time = SI.Update_Date_Time; " +
" " +
" \n\ " +
" SELECT ST.manufacturer, ST.name, ST.model, ST.os, ST.status, " +
" count(status) as CountStatus, " +
" SI.Coord, ST.Last_Update_Date_Time FROM " +
" ( " +
" select s.manufacturer, s.name, s.model, s.os, s. status, " +
" concat(DATE(s.last_update_date),' ',TIME(s.last_update_time)) as Last_Update_Date_Time " +
" from sts s " +
" order by Last_Update_Date_Time DESC " +
" ) AS ST JOIN " +
" ( " +
" select DISTINCT CONCAT(si.latitude, ', ', si.longitude) as Coord, " +
" concat(DATE(update_date),' ',TIME(update_time)) as Update_Date_Time " +
" from sts_info si " +
" order by Update_Date_Time DESC " +
" ) AS SI ON ST.Last_Update_Date_Time = SI.Update_Date_Time " +
" group by status; "
, function (err, rows) {
if (!err) {
console.log("Database is connected... \n");
console.log('The solution is: ', rows[0]);
console.log('The solution is: ', rows[1]);
} else {
console.log("Error connecting database... \n");
console.log('Error while performing Query.');
}
console.log(rows[0]);
console.log(rows[1]);
res.end(JSON.stringify(rows[0]));
res.end(JSON.stringify(rows[1]));
});
});
var server = app.listen(8000, function () {
var port = server.address().port;
var host = server.address().address;
console.log('Example app listening at http://' + host + ':' + port);
});
AngularJs
**$scope.chartOpt1 = {
bindingOptions: {
dataSource: "sts"
},**
//Exposes the current URL in the browser address bar
//Maintains synchronization between itself and the browser's URL
//Represents the URL object as a set of methods
myApp.config(function ($routeProvider) {
$routeProvider
// route for the home page
.when('/', {
templateUrl: 'pages/home.html',
controller: 'mainController'
})
// route for the about page
.when('/about', {
templateUrl: 'pages/about.html',
controller: 'aboutController'
})
// route for the contact page
.when('/contact', {
templateUrl: 'pages/contact.html',
controller: 'contactController'
})
.when('/devicessts', {
templateUrl: 'pages/devicessts.html',
controller: 'devicesController'
})
.when('/sts', {
templateUrl: 'pages/sts.html',
controller: 'stsController'
});
// $locationProvider.html5Mode(true);
});
The result of the page:
Look at the data grid and pie chart aren't being showed in the page.
How do I retrieve the results from query to the angular?
Thank you

If you want get 2 responses you should :
post 2 request
OR
replace this
res.end(JSON.stringify(rows[0]));
res.end(JSON.stringify(rows[1]));
by this
res.end(JSON.stringify([rows[0],rows[1]]));
But a single http request can't send 2 responses

Related

Getting variable from webview to react native

I have a function in a webview which has response:
var respMsg = function(e)
{
var respData = eval("(" + e.data + ")");
document.getElementById("response").innerHTML = e.origin + " SENT " + " - " +
respData.responseCode + "-" + respData.dataKey + "-" + respData.errorMessage;
document.getElementById("response").style.display = 'none';
}
My question is: how to get for example respData.dataKey in a react native value so I can use it further (for example to get it and log its value)

web3 - event.watch spits out events in random order

I am watching an event:
var events = EthProj.Message({}, { fromBlock: 0, toBlock: 'latest'});
events.watch((error, results) => {
Inside the event I do this tempString = ((messages.split(":")[1].split(",")[0] + " (From: " + messages.split(":")[2].split("}")[0]) + ")").replace(/"/g, ''); Which, long story short, makes a string from the event giving the event from the block (i.e. It gives the event made at block 173).
I then set a <h2> element's text from each event. When this happens it sets them in a seemingly random order. What can be going on, it sets them from block 0 to the latest block, so how can this happen.
Here is the full code: https://pastebin.com/wGt5kL1Y
var events = EthProj.Message({}, { fromBlock: 0, toBlock: 'latest'});
events.watch((error, results) => {
i++;
messages = "";
messages = JSON.stringify(results.args);
if(i === messageToGet) {
if(messages.split(":")[1].split(",")[0] != '""') {
console.log(messages.split(":")[1].split(",")[0] + " (From: " + messages.split(":")[2].split(",")[0].split("}")[0].split("}")[0] + ")");
tempString = ((messages.split(":")[1].split(",")[0] + " (From: " + messages.split(":")[2].split("}")[0]) + ")").replace(/"/g, '');
} else {
console.log("(No included text)" + "(From: " + messages.split(":")[2].split(",")[0].split("}")[0] + ")");
tempString = (("(no included text) " + " (From: " + messages.split(":")[2].split("}")[0]) + ")").replace(/"/g, '');
}
if((messages.split(":")[1].split(",")[0] === undefined) || (messages.split(":")[2].split(")")[0] === undefined)) {
return;
}
if(document.getElementById("Message" + placeToSet) != null) {
document.getElementById("Message" + placeToSet).remove();
if(document.getElementById("hr" + placeToSet) != null) {
document.getElementById("hr" + placeToSet).remove();
}
}
if(document.getElementById("Message" + placeToSet) === null) {
var newh2 = document.createElement('h2');
newh2.setAttribute("id", ("Message" + placeToSet));
var text = document.createTextNode(tempString);
newh2.appendChild(text);
document.body.appendChild(newh2);
var newHR = document.createElement('hr');
newHR.setAttribute("id", ("hr" + placeToSet));
}
}
});

node mssql binding in query

I'm new to SQL Server. When I was using MySQL, it was so easy to bind variables using '?'. However, I don't know how to bind variables in mssql.
I tried this:
const pool = new SQL.ConnectionPool(config, function (err) {
console.log('Connected to SQL server successfully');
});
var Myquery = "INSERT INTO person (idNumber, forename, surname, age, address, maritalStatus)" +
" VALUES( " + req.body.idNumber + ", " + req.body.forename + ", " + req.body.surname +
", " + req.body.age + ", " + req.body.address + ", " + req.body.maritalStatus + " )";
pool.request().query(Myquery, function (err, result) {
res.json(result);
})
I get this error:
Invalid column name 'single'.
However, when I execute the query I created here (Myquery) directly in SQL Server, it goes smoothly. How can I fix this?
edit:
const pool = new SQL.ConnectionPool(config, function (err) {
console.log('Connected to SQL server successfully');
});
const ps = new SQL.PreparedStatement(pool);
ps.input('param', SQL.NVarChar);
ps.prepare('SELECT * FROM #param', function (err) {
if (err) console.log('error: ' + err);
else {
ps.execute({param: 'person'}, function (err, result) {
console.log(result);
})
}
});
error: ConnectionError: Connection not yet open.
I used this too:
const pool = new SQL.ConnectionPool(config, function (err) {
console.log('Connected to SQL server successfully');
});
pool.request().input('param', SQL.NVarChar, 'person')
.query("SELECT * FROM #param", function (err, result) {
if (err) console.log('error: ' + err);
console.log(result);
});
error: ConnectionError: Connection is closed.
You need single quotes around your text values:
const pool = new SQL.ConnectionPool(config, function (err) {
console.log('Connected to SQL server successfully');
});
var Myquery = "INSERT INTO person (idNumber, forename, surname, age, address, maritalStatus)" +
" VALUES( " + req.body.idNumber + ", '" + req.body.forename + "', '" + req.body.surname +
"', " + req.body.age + ", '" + req.body.address + "', '" + req.body.maritalStatus + "' )";
pool.request().query(Myquery, function (err, result) {
res.json(result);
})
Also its a SUPER bad idea to create queries based on inputs this way as it allows SQL injection. You should use #parameters (https://blogs.msdn.microsoft.com/sqlphp/2008/09/30/how-and-why-to-use-parameterized-queries/)

Looping through JSON using Node.js

I am trying to loop through JSON using Node so that I can call a stored procedure in a sql database. the JSON is:
[ { boardid: '1', accesid: '2' },
{ boardid: '2', accesid: '3' },
{ boardid: '8', accesid: '4' } ]
the pseudo code i want to implement is: (I have the UserID)
var data = req.body.addJSON
for each JSON object {
con.query(
"CALL addUserToBoard('" + UserID + "', '" + BoardID + "','" + AccessTypeID + "');",
function(err, result, fields) {
if (err) throw err;
}
);
}
You can always interate in an Object a follows
var jsonresponse = JSON.parse(data);
Object.keys(jsonresponse).forEach( function(param , index) {
console.log(jsonresponse[param]);
console.log(index);
});
You could do this using a simple forEach,
var data = req.body.addJSON
data.forEach(value => {
con.query("CALL addUserToBoard('" + UserID + "', '" + value.boardid + "','" + value.accesid + "');", function (err, result, fields)
{
if (err) throw err;
});
})

PhoneGap jquerymobile SQL dynamic link

I am building a PhoneGap iOS App with the help of the jquery-mobile framework. I have a primary jquery-mobile autodivided list, populated by an SQL database. This autodivided list work as expected. When clicking on one link of this dynamic list, a dynamic page is supposed to fire up, containing some extra details included in the same SQL database. However, when the database doesn't load the page details.
I successfully made this work outside jquerymobile framework, with a few script changes. But I really need the autodividers function coming from jquerymobile.
First I assumed that this dynamic page was outside the DOM, but adding the following function at mobileinit() doesn't solve my SQL loading issue:
$( 'fooddetails.html?id' ).live( 'pagebeforecreate',function(event, ui){
alert( 'This page was just inserted into the dom!' );
});
Below is a complete script for my database & the dynamic URL to fire the extra details page:
var db;
var dbCreated = false;
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
db = window.openDatabase("FoodDirectoryDB", "1.0", "PhoneGap", 200000);
if (dbCreated)
db.transaction(getAlimentaries, transaction_error);
else
db.transaction(populateDB, transaction_error, populateDB_success);
}
function transaction_error(tx, error) {
$('#busy').hide();
alert("Database Error: " + error);
}
function populateDB_success() {
dbCreated = true;
db.transaction(getAlimentaries, transaction_error);
}
function getAlimentaries(tx) {
var sql = "select e.id, e.foodName, e.groupfoodName, e.quantity, e.picture, count(r.id) reportCount " +
"from food e left join food r on r.managerId = e.id " +
"group by e.id order by e.foodName ";
tx.executeSql(sql, [], getAlimentaries_success);
}
function getAlimentaries_success(tx, results) {
$('#busy').hide();
$('#foodList li').remove();
var len = results.rows.length;
for (var i=0; i<len; i++) {
var food = results.rows.item(i);
console.log(food.foodName);
$('#foodList').append('<li><a href="fooddetails.html?id=' + food.id + '">' +
'<img src="pics/' + food.picture + '" class="arrow-r"/>' +
'<p class="line1">' + food.foodName + '</p>' +
'</a></li>');
$( 'employeedetails.html?id' ).live( 'pageshow',function(event, ui){
alert( 'This page was just inserted into the dom!' );
});
}
$('#foodList').listview('refresh');
db = null;
}
function populateDB(tx) {
$('#busy').show();
tx.executeSql('DROP TABLE IF EXISTS food');
var sql =
"CREATE TABLE IF NOT EXISTS food ( "+
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"foodName VARCHAR(50), " +
"groupfoodName VARCHAR(50), " +
"quantity VARCHAR(50), " +
"portion VARCHAR(50), " +
"managerId INTEGER, " +
"glucides VARCHAR(30), " +
"picture VARCHAR(200))";
tx.executeSql(sql);
tx.executeSql("INSERT INTO food (id,foodName,groupfoodName,managerId,quantity,portion,glucides,picture) VALUES (1,'Abricot','Fruits frais et fruits secs',1,'1 abricot','65g','5','fruits_legumes.png')");
tx.executeSql("INSERT INTO food (id,foodName,groupfoodName,managerId,quantity,portion,glucides,picture) VALUES (2,'Abricots secs','Fruits frais et fruits secs',1,'4 abricots secs','80g','30','fruits_legumes.png')");
I was also trying to add data-ajax="false" rel"external" to this dynamic link, but this doesn't change unfortunately and I read that these attributes in a dynamic link are not authorized:
$('#foodList').append('<li><a href="fooddetails.html?id=' + food.id + '">' +
Below is the script of the details dynamic page that doesn't load correctly:
var id = getUrlVars()["id"];
var db;
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log("opening database");
db = window.openDatabase("FoodDirectoryDB", "1.0", "PhoneGap", 200000);
console.log("database opened");
db.transaction(getAlimentary, transaction_error);
}
function transaction_error(tx, error) {
$('#busy').hide();
alert("Database Error: " + error);
}
function getAlimentary(tx) {
$('#busy').show();
var sql = "select e.id, e.foodName, e.groupfoodName, e.managerId, e.quantity, e.portion, e.glucides, " +
"e.picture, m.foodName managerFirstName, m.groupfoodName managerLastName, count(r.id) reportCount " +
"from food e left join food r on r.managerId = e.id left join food m on e.managerId = m.id " +
"where e.id=:id group by e.groupfoodName order by e.groupfoodName, e.foodName";
tx.executeSql(sql, [id], getAlimentary_success);
}
function getAlimentary_success(tx, results) {
$('#busy').hide();
$('#foodList li').remove();
var food = results.rows.item(0);
$('#foodPic').attr('src', 'pics/' + food.picture);
$('#foodName').text(food.foodName);
$('#foodgroupName').text(food.groupfoodName);
$('#foodQuantity').text(food.quantity);
$('#foodPortion').text(food.portion);
console.log(food.glucides);
if (food.glucides) {
$('#actionList').append('<li><a href="tel:' + food.glucides + '"><p class="line1">Teneur en Glucides</p>' +
'<p class="line2">' + food.glucides + '</p><img src="img/food.png" class="action-icon"/></a></li>');
}
$('#foodList').listview('refresh');
db = null;
}
function getUrlVars() {
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}