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?
Related
I am working on a node.js app where I am using socket.io to send data to multiple clients but the socket is only able to send data to one client i.e if I open my webpage in two tabs its not working in both the tabs but when I open just 1 tab of webpage it is able to transmit the data.I dont know why? Can someone help,Here's my code:
server.js
var http = require("http"),
io = require("socket.io"),
fs = require("fs"),
util = require("util");
var backlog_size = 2000;
var filename = process.argv[2];
if (!filename) return util.puts("Usage: node <server.js> <filename>");
var linesCount = 0;
// -- Node.js HTTP Server ----------------------------------------------------------
server = http.createServer(function (req, res) {
console.log(req.url)
filePath = req.url
if(filePath=="/"){
filePath='./index.html'
fs.readFile(filePath, function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading ' + filePath);
}
res.writeHead(200);
res.end(data);
});
}
else
{
if(filePath=="/client"){
filePath = './client.html';
fs.readFile(filePath, function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading ' + filePath);
}
res.writeHead(200);
res.end(data);
});
}}
});
server.listen(8000, "0.0.0.0");
var fsTimeout
var textToSend=""
// -- Setup Socket.IO ---------------------------------------------------------
var socket = io(server, {
cors: {
origin: "*",
},
});
socket.on("connection", function (client) {
fs.watchFile(filename, function (curr, prev) {
console.log("file changed");
if (prev.size > curr.size) return { clear: true };
if(!fsTimeout){
if(prev.ctime.getTime() != curr.ctime.getTime())
{
console.log("file changed")
var stream = fs.createReadStream(filename, {
start: prev.size,
end: curr.size,
});
stream.on("data", function (lines) {
console.log(lines.toString());
textToSend+=lines.toString();
textlen=textToSend.split("\n").length;
// count=lines.toString().split("\n").length
// linesCount += count;
// console.log(linesCount);
console.log(textlen)
if(textlen<10)
{
console.log("me")
client.emit("tail", { lines: lines.toString("utf-8").split("\n") });}
else
{
console.log("client")
client.emit("room", { lines: textToSend.toString("utf-8").split("\n") }); };
});
}
fsTimeout = setTimeout(function() { fsTimeout=null }, 5000)}
}
);
});
In the above code I have added 2 clients,1 page is index.html and other is client.html and both are opening in the browser and getting connected to the socket but the data is not transmitting to any of them.Here's are my client codes:
index.html
<!DOCTYPE html>
<html>
<head>
<title>Websockets tail Server</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="/socket.io/socket.io.js"></script>
</head>
<body>
<div id="info" class="trebuchet"></div>
<div id="tail" class="monospace selection"></div>
<script type="text/javascript">
(function() {
var lines = 0, notice = $("#info"), buffer = $('#tail');
var socket = io.connect('http://127.0.0.1:8000/');
socket.on('connect', function() {
console.log('Connected to stream');
});
socket.on('room', function(msg) {
console.log("Message:");
console.dir(msg);
buffer.append(msg.lines.join('<br/>'));
buffer.scrollTop(lines*100);
lines = lines + msg.lines.length;
});
})();
</script>
</body>
</html>
client.html
<!DOCTYPE html>
<html>
<head>
<title>Websockets tail Server</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="/socket.io/socket.io.js"></script>
</head>
<body>
<div id="info" class="trebuchet"></div>
<div id="tail" class="monospace selection"></div>
<script type="text/javascript">
(function() {
var lines = 0, notice = $("#info"), buffer = $('#tail');
var socket = io.connect('http://127.0.0.1:8000/');
socket.on('connect', function() {
console.log('Connected to stream');
});
socket.on('tail', function(msg) {
console.log("Message:");
console.dir(msg);
buffer.append(msg.lines.join('<br/>'));
buffer.scrollTop(lines*100);
lines = lines + msg.lines.length;
});
})();
</script>
</body>
</html>
Both the html files above are my clients and I want them to listen to my socket server but they are not but when I remove one of the clients,it works.
Any help will be appreciated
I am just practicing with API calls and request, by building a simple web app using the Openweatherapi from Openweather.org. It just allows you to type the name of city, and use a button to submit it. The data is fetched, and a description of the city's weather is returned.
Here is the HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Weather App</title>
<link rel="stylesheet" href="/css/main.css">
</head>
<body>
<input type="text" id="cityName">
<br>
<button id="citySubmit">Submit city to get weather</button>
<div id="weatherResponse"></div>
<script src="js/main.js"></script>
</body>
</html>
Here is the Javascript:
const button = document.getElementById('citySubmit');
const citySearch = document.getElementById('cityName');
const getJSON = async (api) => {
try {
const response = await fetch(api);
if(!response.ok) // check if response worked (no 404 errors etc...)
throw new Error(response.statusText);
const data = await response.json(); // get JSON from the response
return data; // returns a promise, which resolves to this data value
} catch(error) {
return error;
}
}
/*
//Call funciton and make http request:
console.log("Fetching data...");
getJSON(apiCall).then(data => {
console.log(data);
}).catch(error => {
console.error(error);
});*/
console.log("Fetching data...");//Just to see if it's working.
getJSON(apiCall).then(data => {
console.log(data);
}).catch(error => {
console.error(error);
});
button.addEventListener("click", function(){
//As you can see, Tampa is hard-coded into the API call
const apiSearch = 'http://api.openweathermap.org/data/2.5/weather?q=tampa&appid={API Key}';
console.log("Fetching data...");
getJSON(apiSearch).then(data => {
const cityName = data.name;
const country = data.sys.country;
const description = data.weather[0].description;
//Weather reponse div
document.getElementById('weatherResponse').append(`The weather in ${cityName}, ${country} is ${description}.`);
})/*.catch(error =s> {
console.error(error);
});*/
})
As you can see, Tampa is hard-coded into the API call (omitted the key), so when the button is pressed, it will just return Tampa's weather. If the request is done this way it works.
Here is the documentation for call examples:
api.openweathermap.org/data/2.5/weather?q={city name}&appid={API key}
When I try to make the request by writing it like this, using a variable as an argument that takes the city submitted to the input field: http://api.openweathermap.org/data/2.5/weather?q='+ citySearch +'&appid={API key} it throws a 404 error.
The API call definitely works as long as the city is hard-coded into the request. I'm not sure what I'm doing wrong. I've also used the brackets given in the example but that's probably wrong. Am I using the variable in the API call incorrectly? I'm stumped.
I am trying to create an API using a local server for testing. The ROUTES are working and I can add data to the OBJ using the URL from the browser. The issue is when I try to 'POST' the data through the HTML. I am getting back a 404 error. I developing using node.js and Express. What am I doing wrong?
JS on the server side
app.get('/add/:word/:score?', addWord);
//Function to request and send back the data
function addWord(request, response) {
var data = request.params;
var word = data.word;
var score = Number(data.score);
var reply;
if (!score) {
var reply = {
msg: 'Score is required'
}
response.send(reply);
} else {
words[word] = score;
// Transforms javascript object into raw data correctly idented with null, 2
var data = JSON.stringify(words, null, 2);
fs.writeFile('words.json', data, finished);
function finished(err) {
console.log('Writting');
var reply = {
word: word,
score: score,
status: 'Success'
}
response.send(reply);
}
}
}
POST method JS
$('#submit').on('click', function submitWord() {
var word = $('#fieldWord').val();
var score = $('#fieldScore').val();
$.ajax({
type: 'POST',
url: '/add/' + word + "/" + score,
success: function (newOrder) {
$list.append('<li>name: ' + newOrder.word + newOrder.score + '</li>');
},
error: function (err) {
console.log('Error saving order', err);
}
});
});
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Tutorial API with node.js</title>
<script type="text/javascript" src ="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<p>
Word: <input type="text" id="fieldWord"><br/>
Score:<input type="text" id="fieldScore"><br/>
<button type="button" id ="submit">Submit</button>
<ul id="list">
</ul>
</p>
</body>
<script type="text/javascript" src="sketch.js"></script>
</html>
Thank you in advance.
I'm new to js. Recently I want to implement a feature, there's a button on the page to get data, click Access database after data showing on the page, the database with MySQL server are using nodejs to build, how to write it with nodejs.
XML/HTML code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<button>get</button>
<!-- show data -->
<div id="res"></div>
</body>
<script src="node_getdata.js"></script>
</html>
JavaScript code
var http = require("http");
var mysql = require("mysql");
var conn = mysql.createConnection({
host : "localhost",
user : "root",
password : "",
database : "test"
});
conn.connect();
conn.query("select * from person", function(err,results){
if(err){
console.log(err);
return;
}
console.log("Result", results);
});
You can create a web server with use of Express framework, which could look like that (very simple example):
var express = require('express');
var app = express();
var mysql = require('mysql');
var conn = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'test'
});
conn.connect();
app.get('/test', function(request, response){
conn.query('select * from persons', function(error, results){
if ( error ){
response.status(400).send('Error in database operation');
} else {
response.send(results);
}
});
});
app.listen(3000, function () {
console.log('Express server is listening on port 3000');
});
Of course you should transform the result of the database operation, probably to some JSON format in order to obtain it in readable form.
Then, you can simply call your REST api with use of XMLHhttpRequest if you want to use plain Javascript.
function getPersons() {
var xmlHttpRequest = new XMLHttpRequest();
xmlHttpRequest.onreadystatechange = function() {
if ( xmlHttpRequest.readyState == XMLHttpRequest.DONE && xmlHttpRequest.status == 200 ) {
document.getElementById("persons").innerHTML = xmlHttpRequest.responseText;
}
};
xmlHttpRequest.open('GET', 'http://localhost/test', true);
xmlHttpRequest.send();
}
And, in order to perform the HTTP call, you can define a button with onClick event:
<button type='button' onclick='getPersons()'>Get persons!</button>
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>