I'm making javascript call python result, but the new data not came back from .py script / or document.getElementById("demo").innerHTML not activate
environment: windows, python, and I open with live server in visual studio code
<!DOCTYPE html>
<html>
<body>
<p id="demo">original data</p>
<script type="text/javascript">
const spawner = require('child_process').spawn;
const data_to_pass_in ={
data_sent:'Send this to python script',
data_returned: undifined
};
console.log('Data sent to py script:', data_to_pass_in);
const python_process = spawner('python',['./get_sql_where_02.py', JSON.stringify(data_to_pass_in)]);
python_process.stdout.on('data',(data)=>{
console.log('Data receive from py script:',JSON.parse(data.toString()));
});
document.getElementById("demo").innerHTML = data_to_pass_in;
</script>
</body>
</html>
get_sql_where_02.py
import mysql.connector
import webbrowser
import time
import pymysql
import sys
import ast
mydb = mysql.connector.connect(
host="196.8.98.141",
user="root",
password="password",
database="data_db",
auth_plugin='mysql_native_password'
)
mycursor = mydb.cursor()
mycursor.execute("SELECT P_TITLE,P_PRODUCT FROM webpage WHERE P_ID = '001'")
myresult = mycursor.fetchall()
print(myresult)
data_to_pass_back = myresult
result picture
I just learn js for few hour so maybe is a simple question, that I need javascript call python result on web
Related
Hi I am working with IOTA distributed ledger. I have iota client library for node.js.
I want to read data from node.js file where I access IOTA distributed ledgers and pass it to Html where user can see.
My client.js file:
const Iota = require('#iota/core');
const Extract = require('#iota/extract-json');
const iota = Iota.composeAPI({
provider: 'https://nodes.devnet.iota.org:443'
});
let x = [];
iota.getBundlesFromAddresses(['PXMPEGYZCOVEOSRAUXY9VYRBHJBSDWORWQNBDJRVEFTMXZWLTQZSPHEUDMXT9YKGPMMSVDSNHSJNWQUOX'])
.then(bundle => {
for (let i = 0; i < bundle.length; i++) {
console.log(JSON.parse(Extract.extractJson(bundle[i])).message);
x[i]=JSON.parse(Extract.extractJson(bundle[i])).message;
}
})
.catch(err => {
console.error(err);
});
I want to pass x[i] variable to html.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="client">
{{ x[0]}}
{{ x[1]}}
{{ x[2]}}
</div>
<script src="myApp.js"></script>
<script src="client.js"></script>
</body>
</html>
I know how to read data from controller but how am I gonna read data if client.js has imported libraries.
I tried in Angular to convert libraries to typescript but couldnt figure out.
This is typically done in package.json, such as server or build
Still most potential for a GUI to Haskell for me, but missing some essential info in the examples, being a noob Haskeller. Assuming one of the examples:
{-
webviewhs
(C) 2018 David Lettier
lettier.com
-}
{-# LANGUAGE
OverloadedStrings
#-}
import qualified Graphics.UI.Webviewhs as WHS
main :: IO ()
main =
WHS.createWindowAndBlock
WHS.WindowParams
{ WHS.windowParamsTitle = "webviewhs - How do I create a window and have it run itself?"
-- This could be a localhost URL to your single-page application (SPA).
, WHS.windowParamsUri = "https://lettier.github.com"
, WHS.windowParamsWidth = 800
, WHS.windowParamsHeight = 600
, WHS.windowParamsResizable = True
, WHS.windowParamsDebuggable = True
}
This creates a window in which I can load a custom webpage. Assuming this webpage has a <input type="text" id="mytext"> and there's a button next to it. Not that it matters but <button type="submit" id="sendtohaskell">. How would I go about getting the info in the textfield to Haskell by pressing the button? There's no example like that in the tutorial. For me it is the missing link to get info from a webapp, processing it in Haskell and returning it to eg. SQLite.
As the github page shows, you can receive data from JS with a callback, and execute arbitrary JS in the window from Haskell. This is enough to do any sort of communication you might want, here's an example that that executes some Haskell on a button press and then shows the result in the webpage:
{-# LANGUAGE OverloadedStrings, QuasiQuotes #-}
module Main where
import System.Directory(getCurrentDirectory)
import Text.Printf
import Control.Monad(void)
import Language.Javascript.JMacro
import qualified Graphics.UI.Webviewhs as WHS
import qualified Data.Text as T
windowCallback window = do
return True
handleJSRequest window request = void . WHS.runJavaScript window $ [jmacro|
show_response `(printf "'Got response: %s'" request :: String)`
|]
main :: IO ()
main = void $ do
dir <- getCurrentDirectory
WHS.withWindowLoop
WHS.WindowParams
{ WHS.windowParamsTitle = "Test"
, WHS.windowParamsUri = T.pack $ printf "file://%s/example.html" dir
, WHS.windowParamsWidth = 800
, WHS.windowParamsHeight = 600
, WHS.windowParamsResizable = True
, WHS.windowParamsDebuggable = True
}
handleJSRequest
windowCallback
<html>
<head>
<title>Example</title>
<meta charset="utf-8">
</head>
<body>
<script type="text/javascript">
function show_response(response) {
document.getElementById('response').innerHTML = response;
}
function submit() {
var value = document.getElementById('textbox').value;
window.external.invoke(value)
}
</script>
<input type="text" id="textbox"/>
<input value="say hello" type="button" onclick="submit()"/>
<p id="response"></p>
</body>
</html>
You should note though that the haskell webview library has only 2 commits, the last of which was more than 7 months ago, so it's not exactly being actively developed at the moment.
I'm developing a web application in linux environnement to display image of data array.
So i would like to save images from python plot to jpeg files to be able to display them in a browser. Python code works correctly when executed from the console. But if called with a javascript request it hangs due to plt use, even with pltioff(). done message is send if i remove all plt code.
python :
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from matplotlib import pyplot as plt
import os
import json
curr = os.getcwd()
plt.ioff()
fig, ax = plt.subplots( 1 )
ax.plot([1, 2, 3])
plt.show()
fig.savefig(curr+"/"+'test.jpeg',dpi=224,quality=50)
messJ = json.dumps( "done" )
print('Content-type: text/html')
print("\n")
print "%s" %messJ
html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>my page</title>
</head>
<body >
<input type="button" id="plotsrv" value="plotsrv" />
</body>
</html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="pythonplot.js"></script>
javascript :
document.getElementById('plotsrv').addEventListener('click', trait_Vdatasrv, false);
function trait_Vdatasrv (e) {
var url = 'pyplot.py';
console.log("url:"+url);
$.post(url,{ file:'ncfile' }, function(data){
$('#data').html(data);
console.log("data"+data);
var jsdec=JSON.parse(data);
console.log(jsdec); }
); }
Regards
I finally found ,
it is needed to add matplotlib.use('Agg')
to avoid display output
I have a small Python script which is supposed to send a string to the javascript in my HTML file to be rendered on the page. However, the script is not receiving the data sent to it from the Python file. My code is below:
simple.html:
<html>
<body>
<h1>Hello</h1>
<p1 id="demo"></p1>
<script>
var s = {{to_display}};
var x = document.getElementById("demo");
x.innerHTML = s;
</script>
</body>
</html>
main.py:
from bottle import Bottle, template
app = Bottle()
#app.route('/')
def index():
data = {"to_display":"HI, how are you"}
return template("simple.html", data)
if __name__ == '__main__':
app.run()
I would like the page to look like this:
Hello
HI, how are you
Unfortunately, it is only displaying:
Hello
Does anyone know how to correct this issue?
The problem here is that the template is not rendering valid javascript.
>>> from bottle import template
>>> data = {'to_display': 'HI, how are you'}
>>> rendered = template('/home/kev/tmp/test.html', data)
>>> print rendered
<html>
<body>
<p1 id="demo"></p1>
<script>
var s = HI, how are you;
var x = document.getElementById("demo");
x.innerHTML = s;
</script>
</body>
</html>
Loading this html in the browser raises a syntax error (tested on Firefox 52.3.0):
SyntaxError: missing ; before statement
The problem is that the definition of s is not quoted within the <script> tag. Fixed version:
<html>
<body>
<p1 id="demo"></p1>
<script>
var s = "{{ to_display }}";
var x = document.getElementById("demo");
x.innerHTML = s;
</script>
</body>
</html>
Renders to this markup, which works as expected in the browser:
>>> print rendered
<html>
<body>
<p1 id="demo"></p1>
<script>
var s = "HI, how are you";
var x = document.getElementById("demo");
x.innerHTML = s;
</script>
</body>
</html>
I want to read the status of my digital pins of arduino and want to display it
in web page. For web programming i am using Flask. I tried this code but its not working. from arduino side I am reading the values of 6 digital pins in the form of 1 and 0. How i can do this? Any help would be appreciated.
<!doctype html>
<html>
<head>
</head>
<body>
<h1 style="font-size:30px;font-family:verdana;"><b>STATUS READ </h1><br><br>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<p id="#status1"></p>
<p id="#status2"></p>
<p id="#status3"></p>
<p id="#status4"></p>
<p id="#status5"></p>
<p id="#status6"></p>
<script type=text/javascript>
function updatevalues() {
$SCRIPT_ROOT = {{ request.script_root|tojson|safe }};
$.getJSON($SCRIPT_ROOT+"/a",
function(data) {
$("#status1").text(data.m+" %")
$("#status2").text(data.n+" %")
$("#status3").text(data.o+" %")
$("#status4").text(data.p+" %")
$("#status5").text(data.q+" %")
$("#status6").text(data.r+" %")
});
}
</script>
</body>
</html>
Python code:
from flask import Flask, render_template,request,redirect, url_for,jsonify,flash
import flask
from shelljob import proc
import math
import eventlet
eventlet.monkey_patch()
from flask import Response
import serial
import time
from datetime import datetime
import json
import random
from flask.ext.bootstrap import Bootstrap
from flask_bootstrap import WebCDN
app = flask.Flask(__name__)
app.secret_key = 'some_secret'
bootstrap = Bootstrap(app)
app.extensions['bootstrap']['cdns']['jquery'] = WebCDN('//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/')
arduino= serial.Serial( '/dev/ttyACM0' , 9600) #creating object
#app.route('/')
def home():
return render_template('status.html')
#app.route('/a',methods=['GET'])
def a():
mydata=arduino.readline().split(',')
return jsonify(m=float(mydata[0]),n=float(mydata[1]),o=float(mydata[2]),p=float(mydata[3]),q=float(mydata[4]),r=float(mydata[5]))
if __name__ == "__main__":
app.run()
It seems like you're not calling updatevalues in Javascript. You should try with something like this:
setInterval(updatevalues, 1000); //So it runs the function every 1000ms (1 second)