Communicating over serial Port in HTML/PHP with Python - javascript

I have an device connected over "/dev/ttyUSB0" to my RaspberryPi. In Chromium I want to set it on "Remote" with a python-serial script:
import serial
ser = serial.Serial()
ser.baudrate = 9600
ser.port = "/dev/ttyUSB0"
ser.open()
ser.write("REM".encode("utf-8"))
ser.close()
this executes on a HTML ButtonClick Event compared with some js code:
function goPython() {
$.ajax({
url: "serial.py",
context: document.body
}).done(function) {
alert('finished python script');;
});
}
HTML:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<button id="click" onclick="goPython()">GO!</button>
</body>
It runs on my Chromium Browser at the RasPi and says:
finished python script
But the device, sadly isnt in Remote Access. Anybody got a hint? Since I had very positive experiences at StackOverflow I wanted to post it here. Thanks a lot people!

Related

Javascript - ajax refreshing a div with an old version of an updated file

I am making a web dashboard and for this I have a javascript function that loops infinitely, updating a particular div at frequent intervals. (it uses ajax/jquery to do this).
I have used a loop with setTimeout:
<!doctype html>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
function updateMain() {
setTimeout(function() {
console.log("updating");
$('#main').load('new-content.php #main', function() {});
updateMain();
}, 3000)
}
updateMain();
</script>
</head>
<body>
<div id="main">
<p>hi there</p>
</div>
</body>
</html>
'new-content.php' is a file that is constantly updated by another part of my program, to show the new content for the dashboard.
it looks something like this:
<div id="main">
<p>Hello i am updated content</p>
</div>
I am sure the loop is working as the "updating" messages appear at regular intervals in the console.
When the program starts, the div is showing "hello there", and in the new-content.php file it has "hello am updated content".
The first time the loop runs, it updates the div to show "hello i am updated content".
But if I further update the new-content.php file, for example to say "hello I am further updated content", it just won't show on my webpage. However I am sure that the loop is still running as the messages appear in console.
It's like ajax has some cached version of the new-content.php file that it loads at the start then keeps using forever.
I am very confused, if you could help me I would be very grateful
Thank you
PS: if it is of relevance, the website is running through flask but I don't think this is the problem.
EDIT: I believe it is actually a flask caching issue
You can try adding a cache buster to see if that helps. Change your code as follows:
function updateMain() {
setTimeout(function() {
console.log("updating");
const cb = new Date().getTime();
$('#main').load('new-content.php?cb=' + cb + '#main',function() {
updateMain();
});
}, 3000)
}
updateMain();
Wasn't able to solve the issue but for anyone who is trying to make a similar project, I decided to use flask-socketio instead which allows me to send data to javascript to be shown on the page, instead of javascript loading the data itself from a file. (the answer by vladtn on this SO post was useful as an introduction to socketio)

Node.js and PowerShell Commands/Scripts

Here is the folder structure for my node.js project:
MySampleApp\
MySampleApp\Package.json
MySampleApp\Server.js
MySampleApp\public:
index.html - Invoked when server.js starts and shows "Click Me" button
fetchprocess.js - check button click and then show in DocumentElementID
user1.ps1 - runs Get-Process command to fetch processes
fetchprocess.js:
console.log('Client-side code running');
const button = document.getElementById('myButton');
button.addEventListener('click', function(e) {
console.log('button was clicked');
document.getElementById('counter').innerHTML = "ClickedNow";
var ps = new shell({
executionPolicy: 'bypass',
noProfile: true
});
app.get("/", function (req, res) {
ps.addCommand("./user.ps1", [ {
name: 'guid', value: req.params.guid
} ])
ps.invoke().then(output => {
res.end(output); // This is to show the output in web browser
})
})
});
Index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Example</title>
</head>
<body>
<p id="counter">Loading button click data.</p>
<button id="myButton">Click me!</button>
</body>
<script src="fetchprocess.js"></script>
</html>
My objective is to execute "user1.ps1" when someone clicks on the "ClickMe" button and then show the data in HTML Div (Counter). When I try to run above code it throws an error that require is not defined in fetchprocess.js file.
Image:
I will have several scripts under the public folder that will be executed when someone clicks on other buttons on the web app. What is the best folder structure for such project.
Thank you very much
TL; DR; There is no way you can execute Node.js code in a browser.
Looks like you messaged up with libraries. You are trying to execute some Node.js code in the browser.
<script src="fetchprocess.js"></script>
Here you are loading the script in the browser. The truth is that Browser JS code does not have access to the platform things like PowerShell and it is not Node.js at all. If you need to execute Node.js code use Node.js executable.
UPD:
The workaround may be the following.
Spin up HTTP server locally with Node.js
Add an endpoint that runs the PS script once it receives a request.
On-click send AJAX request to your server.
But it worth noticing that it will work only on the machine where the Node.js server is running. Because it is not possible to run PowerShell from a browser.

How to run a python script on remote server by button click on web page?

I have a python program on remote server. I need to create a web page (html code present in same directory as that of python script on server) having a button on clicking which python script should run. One more thing is that we need to choose a file from local machine after which the python script takes that file as input, runs and outputs another file which needs to be displayed on web page.
I don't know what to use javascript or ajax or php to achieve this. I tried out different ways but in vain.
This is the html code I have been trying with...
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
// var file = $('#fileInput')[0].files[0]
var fd = new FormData();
fd.append('fileInput', file);
// console.log(fd)
$.ajax(
{
type: "POST",
url: "./summarize.py",
data: "fd"
success: function (response) {
}
// error: function (response) {}
});
});
});
</script>
</head>
<body>
<h3>Upload reviews file</h3>
<input type="file" id="fileInput" name="fileInput">
<p>Click the "Get summary" button to summarize the reviews.</p>
<button>Get summary</button>
</body>
</html>
I have searched online but no where the answer was specific (I felt so). Since I am new to javascript, I have trouble in following them. Someone kindly explain what is to be done.
Thank you.
I think you can use php exec, to run Python and your summarize.py script.
<?php
// #result array
exec("python summarize.py", $result);
PHP exec will return you result. Also you can use django or other frameworks to run your Python code.

Ajax code is not working in html

I am trying to get all content of two.html in onw.html page by using ajax but don't knw its not working in short in have to develop one page application n url should not load below in have posted my code.
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
// Check browser support
function demo()
{
var name=document.getElementById('dd').value;
if (typeof(Storage) !== "undefined") {
// Store
localStorage.setItem("lastname", name);
// Retrieve
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
}
}
$(document).ready(function(){
$("button").click(function(){
$.ajax({
url: "two.html",
success: function(result){
$("#result").html(result);
}});
});
});
</script>
</head>
<body>
<div id="result"></div>
<input id="dd" type="text" onblur="demo()" >
<br/>
<button>two</button>
<br/>
write something & click on link it will redirect to another page.
close this page and open three.html page.
<br/>
<img src="1.png" alt="da" style="width:150px;height:150px"></img>
</body>
two.html
<!DOCTYPE html>
<html>
<body id="body">
<div id="result"></div>
<label>Second Page</label>
<script>
if (typeof(Storage) !== "undefined") {
document.getElementById("result").innerHTML = localStorage.getItem("lastname");
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
}
</script>
<img src="2.gif" alt="da" style="width:150px;height:150px"></img>
</body>
</html>
Chrome's internal settings are blocking your request because you are not using a supported scheme ie (http, data, chrome, chrome-extension, https, chrome-extension-resource).
Simply put, you are running the file from your desktop so the file address starts with file:// and not http:// or https://
You need to run the file from a server setup as your localhost or upload the files to a remote server.
you could also simplify your code a touch with the shorthand version .get():
$(document).ready(function(){
$("button").click(function(){
$.get( "two.html", function( result ) {
$( "#result" ).html( result );
});
});
});
Apparently, you can also set a flag in chrome to override the scheme requirement, but it would be much preferred to just run the files on a server with the correct scheme, and if you do change the flag, be sure to revert it when you're done testing locally, its there for a reason after all.
On your console i can see many errors.
you are trying to make ajax call without localhost or without any server here.
you not mention its mime-type: "text/html" here.
so 1st you need to know ajax.
Ajax is not work without http or https url. so for that you must need to start localhost or setup any webserver.
and if you want to load your other html file content on your current html page then you can use
$("#results").load("test.html");
but it will works only firefox browser not work on chrome. because chrome-security flag is not allowed you to load files on web browser from your local file system.
if you want it works on chrome also you have two options.
you can make your application as an chrome extention.
first you can setup any local server and start localhost and copy your files in www or webapp directory and then try for Ajax.
try this if you have setup 2nd step.
$("button").click(function(){
/* you can make ajax by 2 ways 1st ways this which used traditionally */
$.ajax({
type:"GET",
url: "two.html",
mimeType: "text/html; charset=utf-8",
success: function(result){
$("#result").html(result);
});
/* 2nd Ajax type is...*/
// $("#result").load("two.html");
});
if you have wamp server then copy your all files and paste on this direcory
"C:\Program Files\wamp\www\" and
start your localhost.
open browser and type localhost
and select your base html file. and then click the button it will works.
I hope it will helps you.

Running Batch file using Javascript - Firefox

This is important for me as I have a PRN file which can be printed only through command prompt. And I want to delete that file after the print command is given.
So these 2 commands can be executed using batch file only.
And when I try to use activexobject in javascript, my firefox browsers doesnt run it.
<script>
MyObject = new ActiveXObject("WScript.Shell");
function Runbat()
{
MyObject.Run("\"D:\\abc.bat\"");
}
</script>
Together in a html page.
I've found this one and it seems working properly :)
<html>
<head>
<script language="JavaScript" type="text/javascript">
MyObject = new ActiveXObject("WScript.Shell")
function Runbat()
{
MyObject.Run("\"D:\\test.bat\"");
}
</script>
</head>
<body>
<h1>Run a Program</h1>
This script launch the file any bat File<p>
<button onclick="Runbat()">Run bat File</button>
</body>
</html>
Now I don't really know if you are already working with exaclty that solution, if so, and you are still facing this issue in firefox you may need to investigate a little bit more in browser security to know if that is even possible as of this post states that:
No, that would be a huge security breach. Imagine if someone could run
format c:
whenever you visted their website.

Categories