Execute query on sqlite database in html script base using javascript - javascript

I'm new in web developing.
I want to query an SQLite database from HTML script balise.
for more details, I share my code.
function test() {
var fullname;
var fname = "bishoy";
const sqlite3 = require('sqlite3').verbose();
let db = new sqlite3.Database('./Basket.db');
let sql = 'SELECT * FROM [Source: players]';
db.each(sql, [fname], (err, row) => {
if (err) {
throw err;
}
fullname = ('${row.Name}');
alert(fullname);;
});
db.close();
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button type="button" onclick="test()" style="font-family:cambria;
">Execute</button>
</body>
</html>
the problem that I encounter when I execute it on my Chrome browser: storage.html:8 Uncaught ReferenceError: require is not defined
at test (storage.html:8)
at HTMLButtonElement.onclick (storage.html:22)
, please someone can help me to fix the problem.

Related

Can't print results to my console with NodeJS

I'm a newbie around here and of course, I am newbie also to the nodejs technology.
I'm writing to you because I have a big problem for me, maybe a little problem for you, with the following:
I have this part of the code and I want when a user clicks on a button then the user should insert 3 values for him: UserId, GameId, Bookid. Then I want with the help of node js to print the results to my console. But i see from F12 that it says there is a problem with this line
loadnodejs.html:9 Uncaught ReferenceError: require is not defined --> var mysql = require('mysql');.
I've done the procedure from w3schools but nothing is showing. Can you help me to print the results on my console?
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
<script>
function load3() {
do{
var selection = window.prompt("Give the User Id:", "Type a number!");
if ( /^[0-9]+$/.test(selection)) {
flag1=false;
}
}while(flag1!=false);
var flag2 = true;
do{
var selection2 = window.prompt("Give the Book Id:", "Type a number!");
if ( /^[0-9]+$/.test(selection2)) {
flag2=false;
}
}while(flag2!=false);
var flag3= true;
do{
var selection3 = window.prompt("Give the Game Id:", "Type a number!");
if ( /^[0-9]+$/.test(selection3)) {
flag3=false;
}
}while(flag3!=false);
var mysql = require('mysql');
var con = mysql.createConnection({
host: "127.0.0.1",
user: "root",
password: "",
database: "mysql3"
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM components", function (err, result) {
if (err) throw err;
console.log(result);
});
});
}
</script>
</head>
<body>
<input type="button" value="Load" id="load" onclick="load3()" class="button12" />
</body>
</html>
Node.js is JavaScript which runs on backend. You have added Node.js code to an HTML file, which runs in browser. Browser doesn't support Node.js and hence the error.
Make an API call to server, and move Node.js code to server. I hope it makes sense to you.
Node.JS is a server-side technology, not a browser technology. Thus, Node-specific calls, like require(), do not work in the browser.
See [browserify]:http://browserify.org/ or webpack if you wish to serve browser-specific modules from Node.

Javascript web application with connecting Odoo

I would like to design Javascript web application. In that application, I need to show reports dashboard like daily sales report, the data to be fetched from odoo application.
So I used odoo-xmlrpc to connect javascript to odoo.
js.file
var Promise = require('promise');
var async = require("async");
var Odoo = require('odoo-xmlrpc');
var odoo = new Odoo({
url: 'localhost',
port: '8063',
db: 'db_1',
username: 'admin',
password: '123'
});
function color(){
return new Promise(resolve => {
odoo.connect(function (err) {
if (err) { return console.log(err); }
console.log('Connected to Odoo server.');
var inParams = [];
inParams.push([[],[]]);
var params = [];
params.push(inParams);
odoo.execute_kw('account.invoice', 'check_func', [[[], []]], function (err, value) {
if (err) { return console.log(err); }
console.log('Result: ', value); //Result: Done
resolve(value);
});
});
});
}
async function changeColor(newColor) {
//document.getElementById("para").innerHTML = "Hello3"; //this line working
var result = await color();
console.log(result, "###########")// Result Done
var elem = document.getElementById('para').innerHTML="tet"; //This line dot working
}
changeColor('red')
check_func() in python
#api.multi
def check_func(self):
return "done"
html file
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script type="text/javascript" src="/home/priya/Desktop/ra.js"></script>
</head>
<body>
<h2 style="text-align:center;">Reports</h2>
<div style="text-align:center;">
<input type="button" onclick="sales_report_retail()" value="Sales report"/>
<p id="para"></p>
</div>
</body>
</html>
In that odoo.execute_kw(), I used resolve(value). That value is working with in odoo.execute_kw().
var result = await sales_report_retail_db(); this line value gets correctly but after this line document.getelementbyid is not working.
I need to show that value in web page. So how to correct this?

Receive data from mysql in node.js to draw graph

I'm learning node.js and i want to write a program that draws a graph of data fetched from mysql database. I am doing the back end processing in the server.js file and showing results in index.html. Since i'm new to node.js and web programming. I don't know how to get data as a javascript object and draw it's graph.
Question:
I want to know how would i send the data fetched into the javascript object to the graph drawing code.
Here is my server.js :
var mysql = require('mysql');
var express = require('express');
var app =express();
var country = [], population = [], gdp = [];
var jsonArray;
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '12345',
database: 'rohan'
});
var queryString = 'SELECT * FROM Country';
// Fetching data from database
app.get('/', function(req, res) {
connection.query(queryString, function(err, rows, fields) {
if(err) throw err;
formatData(rows);
res.send(jsonArray);
console.log(jsonArray);
});
});
function formatData(dataArray) {
for(var i = 0; i < dataArray.length; i++) {
country[i] = dataArray[i].name;
population[i] = dataArray[i].population;
gdp[i] = dataArray[i].GDP;
}
jsonArray = [country, population, gdp];
console.log("in FormatData()...\n");
console.log(jsonArray);
}
app.listen(3000, function() {
console.log("Server listening on port 3000");
});
and this is my index.html:
<html>
<head>
<title>Chart-mysql demo</title>
<script>
// code to draw graph
$("#clients").bind('ajax:success', function(result) {
console.log("In index.html" + result);
alert(result);
var barData = {
label:result.country,
datasets: [
{
label: '2010 Customers #',
fillColor: '#382765',
populationData:result.population
}
]
};
var context = document.getElementById('clients').getContext('2d');
var clientsChart = new Chart(context).Bar(barData);
});
</script>
</head>
<body>
<h1>Country Demographics</h1>
<script src="Chart.js"></script>
<script src="app.js"></script>
<canvas id="clients" width=500 height=400></canvas>
</body>
</html>
As I see you haven't get data from node.js app. First of all you need to somehow retrieve this html from server, so you need to add something like:
app.get('/', function(req, res) {
res.render('index.html');
});
Then you need to change your current app.get('/' to some another url. Let's say "/data".
After that change you need to change your current index.html, and add there JS code, which will request data from "/data". You can use jquery for that. Take a look at http://api.jquery.com/jquery.ajax/ Then you will get an JS object in callback of Jquery ajax request to node.js "/data".
You should first write a module which would fetch the data(you have got a piece of code which connects to the database so we can skip this part).
Then we should write a router which would pass the data to the pathname (when it is called) for example like this:
router.get('/', function(req, res, next) {
api.apiGet(function (data){
-> importing data from module (api is a variable importing the module, apiGet a function from api).
res.render('portal', {result: data}); -> data is passed as result
});
});
Then you would write a view which would use that data, for example in Jade it would be the following.
{val[4].label}
It just grabs the data which is send in JSON.
If you need something clearing just write :)
After hours of head scratching i finally did it.As far as server side was concerned i was doing it right. I just didn't know how to deal with data on the client. To receive data as a javascript object, I added a button and connected an AJAX call to it's onclick() event.
<body>
<h1>Country Demographics</h1>
<button id="Get_Graph" onclick="gData(); return false">Get Graph<button/>
<canvas id="clients" width=500 height=400></canvas>
</body>
And to handle it's click event, here is javascript code:
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="../Chart.js"></script>
<script>
// code to draw graph
function gData() {
$.get("http://localhost:3000", function(result, status) {
alert(result);
var barData = {
labels:result[0],
datasets: [
{
label: '2010 Customers #',
fillColor: '#382765',
data: result[2]
}
]
};
var context = document.getElementById('clients').getContext('2d');
var clientsChart = new Chart(context).Bar(barData);
});
}
</script>

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.

display a message before (or after) a redirect javascript

I'm trying to display a message after or before a redirect. I looked around the site but I found only jquery and php but I can only use the normal java language. In particular I'm trying to use a div that could be good for me. The problem is that the redirect is on the server side (so I cannot call a javascript function or I cannot put a document.getElementByID). Can you help me? Here is my code:
var express = require('express');
var router = express.Router();
var middleware = require('../middleware');
var mongoose = require('mongoose');
var ObjectId = mongoose.Types.ObjectId;
var User = mongoose.model('User');
var config = require("../../config");
var session;
router.all('/', middleware.supportedMethods('GET, POST'));
router.get('/', function(req, res, next) {
res.render('login');
});
router.post('/', function (req, res) {
var post = req.body;
var query = User.where({userName : post.username});
query.findOne(function(err, user){
if (err) { return err}
if (user) {
user.isValidPassword(post.password, function(n, isMatch){
if(isMatch) {
req.session.user_id = user._id;
res.redirect('/library?' + user._id);
} else{
res.redirect('/login');
}
});
}else{
res.redirect('/login');
}
});
});
module.exports = router;
I would put my message on the res.redirect('/login') (both of them) with two different message. I don't know if I have to create a new page, identical, with a div message or I could find a better solution...
I'm trying to display a message after or before a redirect...The problem is that the redirect is on the server side (so I cannot call a javascript function or I cannot put a document.getElementByID).
Exactly. So you can't do that. Instead, you need to return a redirect to a page with your message on it, and then have that page continue on (after a period of time, or after a user action) to the ultimate destination (/login or whatever).
A minimal intermediary page might look like this:
<!doctype html>
<html>
<head>
<title>Some Relevant Title</title>
<meta charset="utf-8"></meta><!-- Or whatever is appropriate -->
<meta http-equiv="refresh" content="15; url=/login">
</head>
<body>
Message goes here. With the refresh above, the page will refresh after 15 seconds.
</body>
</html>

Categories