How to run Python script from Javascript on Apache web server? - javascript

Cannot get HTML file to call JavaScript function hello() on Ubuntu Apache 2. I have seen similar problems where the solution was to uncomment the #JSDIR line on the httpd.conf file but there is now only apache.conf and no similar line. I want to call the python script accesstest.py to write the current date and time to a text file from the main.js function after clicking the button on the HTML file. All of the files work correctly when run separately. How do I fix this?
index.html HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<title><demo</title>
</head>
<body>
<h1></h1>
<script src="main.js"></script>
<button onclick="hello();">js function</button>
</body>
</html>
main.js JavaScript code:
let myHeading = document.querySelector('h1');
myHeading.textContent = 'Hello world!';
function hello(){
var spawn = require("child_process").spawn;
var process = spawn('python,["accesstest.py"]);
alert('hello');
}
accesstest.py Python code:
import datetime
def execute():
file = open('/path/to/file/pytest.txt', 'a+')
file.write('test time: %s \n' % (datetime.datetime.now()))
file.close()
execute()
Here is the display:
page displays "Hello World!" with "js function button" that does nothing
Here are a couple solutions I found that didn't work for me:
Unable to call JavaScript function in html on button click
How to link external javascript file onclick of button
Thanks.

Related

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 can I import/require a uploaded JS File into my javascript

I want to be able to upload some JS Files (Self-Programmed Bots for a game) and then be able to execute the code inside them.
Currently the User is required to have the Programm in a certain directory and I take the file from there like this:
this.bot = require('../bots/' + file.name);
Is there a better way to do this that, if possible, also works when the Website is running on a Server (I'm not sure if my current solution would)?
try like this
index.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script type="module" src="script2.js"></script>
</body>
</html>
script1.js
export default function Hello() {
return "Hello buddy!";
}
script2.js
import { Hello } from './script1.js';
let val = Hello;
console.log(val);

How to execute javascript code inside an HTML page that was requested by the Fetch API?

The only related question I found for my issue is this one:
page fetched by AJAX cannot execute any javascript
But I don't want do use JQuery. I want to use vanilla javascript.
The problem is that I can't execute any javacript that is inside an html page that is fetched using the fetch api.
Here are my files:
index.html: This is the initial HTML page. It requests a file called index.js as an ES6 module
<!DOCTYPE html>
<html>
<head>
<script type="module" src="index.js"></script>
</head>
<body>
<main id="content" role="main"></main>
</body>
</html>
Then I have my index.js file:
import openTemplate from './shared-assets/js/openTemplate.js';
const target = document.getElementById('content');
openTemplate('dashboard.html', target);
This is the openTemplate.js file:
export default function openTemplate(templatePath, targetElement){
fetch(templatePath).then(response => {
response.text().then(html => targetElement.innerHTML = html);
});
}
And finally, the dashboard.html template that refuses to execute javascript:
<h1>Dashboard</h1>
<script type="module">
import myAlertFunction from 'myAlertFunction.js';
// this is just a function that encapsulates an alert call
// my real code will have much more complex functions being imported
myAlertFunction('test');
</script>
All this code should result in a scenario in which, when my index.html page loads, an alert should display with the text 'test', but this is not happening.
I want this to run on Firefox Quantum >= 66
What am I missing?

Electron storing javascript functions

I have created a new electron application.
It consists of the following files:
index.html
main.js
renderer.js
In the index.html I have added a button with an onclick event:
<button onclick="myfunction()">Call Function</button>
And the function is just an alert for testing purposes:
myfunction() {
alert('I am the js function');
}
My problem is that I've added the function code to both the renderer.js and to the bottom of main.js and when I click the button I see no alert.
How can I get js functions to be called from the index.html?
Let the myFunction reside in a separate javascript file. Let's say it's named "functions.js". To use this function in the HTML file (index.html), simply add the Javascript code using tag in the following manner -
<html>
<body>
...
</body>
<script type="text/javascript" src="./functions.js"></script>
</html>
Now, we will need to attach an onclick listener to the button that is rendered using the HTML code.
To do that, add the following in functions.js
document.getElementById('btn').addEventListener("click", function(){
myFunction();
});

Javascript function defined in <head> is not being called on S3

I have a .json file in a bucket on S3. I'm trying to parse information from the file, a date and a SigninSim. I am doing this through an html file which once I get this figured out will take that parsed information, go into another folder, and display some pictures. Here is the code that I currently have written.
<!DOCTYPE html>
<html>
<head>
<script src="https://s3.amazonaws.com/'BUCKET'/browser.json"></script>
<script type="text/javascript">
function parseJSON()
{
var info = JSON.parse(browser);
document.write(info.date);
document.write(info.SigninSim);
}
</script>
</head>
<body>
<script type="text/javascript">
parseJSON();
</script>
</body>
</html>
When I run this nothing shows up on the page. Any ideas? I'm also very new to html/javascript so I could be doing something completely wrong, anything helps!
<script> tags can only be used to execute Javascript code, not to read JSON files.
Change the JSON file to a Javascript file that creates global variables or objects.

Categories