How to execute python script from a button in HTML page - javascript

I've to run a python script from my HTML page button. When I click on the button, it should run the command "python filename.py". But I'm not getting any solutions, please help!
Thank You

Sorry to say but this is not possible unless your 'filename.py' is on a server e.g. flask, or else this will not work. If setup a flask server, and with a certain route it runs your code, then you can have your HTML code make a POST or GET request to this flask server, and the code should run.

Attach a listener to the button and have that listener call your endpoint:
document.querySelector('button')
.addEventListener(() => fetch('runMyScript.php', { method: 'POST' }));
Then have that endpoint run your desired program. In PHP, for example:
<?php
// if you want the page to be able to do something with the result:
$output = `python /home/username/filename.py 2>&1`;
echo $output;
?>
Of course, a real setup better have something to validate

You can’t.
Python runs in the server. HTML isn’t a programming language, it’s content, and it sits in the browser. About the best you can do is use AJAX to call a function in the server (which you’d have written in Python) and, if it returns a value, return it via AJAX.

Related

Javascript is executing on reload

I am using a php file to create a page that allows me to manage mysql entries. The page fetches the entries from the database and lists them which I have working fine. I am trying to add a button that allows me to "accept" an entry which changes its status value to 1 from 0.
It is working fine, except when I refresh the page, it automatically is executing the javascript function which should be an onclick event. Am I missing something incredibly simple or something. I have been looking at this for 2 days now and have rewritten it several times without success as well as extensive googling to find an answer.
My button:
<input type='submit' name='acceptbut' id='acceptbut' value='Accept'></input>
I am thinking the problem has something to do with either the location.reload or something else.
<script type="text/javascript">
function setAccept() {
<?php
$query = "UPDATE regiments SET status=1 WHERE memberID=$mid";
mysqli_query($connect, $query);
?>
location.reload(true);
}
document.getElementById('acceptbut').onclick = setAccept;
</script>
I have also tried messing with an inline onclick but it is not working either
My confusion is why is the function running if im not actually calling it.
Your PHP executes on the server every time the page is requested. The fact that the PHP is located inside a Javascript function is not relevant.
The PHP server parses the file, finds any PHP in it, runs the PHP on the server, then sends the result to the browser.
If you want to execute some PHP only when a Javascript function is executed in the browser, then you have to make an Ajax call from the Javascript to your server and have the Ajax call request a PHP page that can then run the desired PHP and return a result (if necessary) back to the browser's Javascript.
Keep in mind that in your setup, PHP executes on the server, then the resulting page (without any PHP in it) is sent to the browser. The browser then executes appropriate Javascript in the web page as events occur. The only way to execute code on the server at that point is to make an Ajax call to the server.
You are confusing Client and Server side. Look at this:
function javascriptFunction()
{
<?php echo date("Y"); ?>
return true;
}
The above block of code gets executed in PHP. How? Each line of the above code is treated as a sequence of characters and is sent to the cout (standard output). The small snippet inside the <?php...?> gets executed by PHP and if there are any output, it also is sent to standard output. Only when the characters are sent from server to the client side (browser), the browser starts interpreting them. Which results in a code inside <script type='text/javascript'>..</script> to be interpreted as a JS snippet. Now, bear in mind: EVERY PHP CODE GETS EXECUTED BEFORE THERE ANY THING AS JS, CSS or HTML. PHP SEES EVERYTHING AS EITHER String, Integer/Double or Boolean (etc.).
What you should do?
Learn what is AJAX, and try to learn its best practices. You'll amaze at its excellence.

Execute javascript function attached to a html element in python

What I'm trying to do is what can be done in a browser by running this javascript: document.getElementById('foo').bar().
I don't know how to go about doing this in python. I used to do stuff with submitting forms using twill and sending responses with urllib2, but I never had to do any javascript. Where should I start?
I guess you are building up your html/js code in the server side and when requested, you will serve that code to the client? As client code will be served you can add it to you logic in the server side:
getFooElement = 1;
if getFooElement:
print "document.getElementById('foo').bar()"
else
print "HTML/JS code"

Pass javascript value into PHP variable [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 7 years ago.
I'm trying to include JavaScript variables into PHP code as PHP variables, but I'm having problems doing so. When a button is clicked, the following function is called:
<script type="text/javascript">
function addTraining(leve, name, date)
{
var level_var = document.getElementById(leve);
var training_name_var = document.getElementById(name);
var training_date_var = document.getElementById(date);
<?php
$result = "INSERT INTO training(level, school_name, training_date) VALUES('level_var', 'training_name_var', 'training_date_var')" or die("Query not possible.");
?>
</script>
Is it possible?
PHP is run server-side. JavaScript is run client-side in the browser of the user requesting the page. By the time the JavaScript is executed, there is no access to PHP on the server whatsoever. Please read this article with details about client-side vs server-side coding.
What happens in a nutshell is this:
You click a link in your browser on your computer under your desk
The browser creates an HTTP request and sends it to a server on the Internet
The server checks if he can handle the request
If the request is for a PHP page, the PHP interpreter is started
The PHP interpreter will run all PHP code in the page you requested
The PHP interpreter will NOT run any JS code, because it has no clue about it
The server will send the page assembled by the interpreter back to your browser
Your browser will render the page and show it to you
JavaScript is executed on your computer
In your case, PHP will write the JS code into the page, so it can be executed when the page is rendered in your browser. By that time, the PHP part in your JS snippet does no longer exist. It was executed on the server already. It created a variable $result that contained a SQL query string. You didn't use it, so when the page is send back to your browser, it's gone. Have a look at the sourcecode when the page is rendered in your browser. You will see that there is nothing at the position you put the PHP code.
The only way to do what you are looking to do is either:
do a redirect to a PHP script or
do an AJAX call to a PHP script
with the values you want to be insert into the database.
<script type="text/javascript">
var jvalue = 'this is javascript value';
<?php $abc = "<script>document.write(jvalue)</script>"?>
</script>
<?php echo 'php_'.$abc;?>
You seem to be confusing client-side and server side code. When the button is clicked you need to send (post, get) the variables to the server where the php can be executed. You can either submit the page or use an ajax call to submit just the data.
-don
PHP runs on the server. It outputs some text (usually). This is then parsed by the client.
During and after the parsing on the client, JavaScript runs. At this stage it is too late for the PHP script to do anything.
If you want to get anything back to PHP you need to make a new HTTP request and include the data in it (either in the query string (GET data) or message body (POST data).
You can do this by:
Setting location (GET only)
Submitting a form (with the FormElement.submit() method)
Using the XMLHttpRequest object (the technique commonly known as Ajax). Various libraries do some of the heavy lifting for you here, e.g. YUI or jQuery.
Which ever option you choose, the PHP is essentially the same. Read from $_GET or $_POST, run your database code, then return some data to the client.
I had the same problem a few weeks ago like yours; but I invented a brilliant solution for exchanging variables between PHP and JavaScript. It worked for me well:
Create a hidden form on a HTML page
Create a Textbox or Textarea in that hidden form
After all of your code written in the script, store the final value of your variable in that textbox
Use $_REQUEST['textbox name'] line in your PHP to gain access to value of your JavaScript variable.
I hope this trick works for you.
You can take all values like this:
$abc = "<script>document.getElementByID('yourid').value</script>";
You can do what you want, but not like that. What you need to do is make an AJAX request from JavaScript back to the server where a separate PHP script can do the database operation.

how to access the server side terminal in a webpage at client side?

A terminal emulator has to be embedded in a web page, in which the user has to compile and run his java program created on server by web page access. I want to compile and run the program in terminal. The client not needed to install any application software.
I would recommend the following:
make a text editable div (set the contentEditable attribute to true) and style it to look like a console.
Then bind to its keypress event to monitor for an enter, upon which you ajax request a serverside script that performs whatever you typed. E.g. use php's exec() and output it's return value.
Append the server-side script's response to the div, and repeat..
You should be very careful when opening up the console to the user though. You can further restrict the terminal's ability by explicitly prepending a function to all terminal commands, e.g. <?php echo exec('git '.$_GET['cmdtxt']); ?> is one way to ensure that git is called, but it's still vulnerable since you could potential execute a second command. I'm sure you can figure out what your security needs are and properly validate them.
If this seems vague, it's only because your question isn't all too specific. Is this the answer you were looking for? Let me know :)
First, you can create a div for displaying results and a textarea for the commands. Check for keypress of the textarea and send the command to the server using AJAX when the user presses enter. You can style them to look more terminal-alike.
Beware that expose the console to the users can easily get hacked. Always check the user input to ensure that dangerous commands cannot be executed.
Sample code of how to filter commands:
<?php
$cmd = $_POST['cmd'];
$allowed = array('ls','git','grep','...');//The allowed commands
foreach($allowed as $part){
if(strpos($cmd,$part) === false){
echo 'Command not recognized!';
}
}
ob_start();
passthru($cmd);
$result = ob_end_clean();
echo json_encode(array('result'=>$result));
Hope this can help you.

Is there any way to call JavaScript function from a perl script?

I am trying to write a Perl script that will take a user parameter from command line and with his parameter, Perl script will call a JavaScript function in a HTML page. How can I go ahead to with this?
Not that I've seen. Perl is strictly server side, and JS functions you're talking about are on the client.
The closest you would get is have the Perl script write a block into the HTML page so that the page fires it on load to perform the action. But that's a little shaky at best to do.
It depends on whether the browser or server will be taking the first step.
If the server needs to run code first and then execute some JS, then #skyburner's solution would work. Essentially you would already have some functions defined on the page, but then you would dynamically add a block of JS to call whichever function you need to.
However, if the Perl is being run due to a user's action on the current page (such as clicking something or submitting a form), then AJAX would be the way to go. You would use JS to submit an HTTP request to the Perl script. The Perl would then return some value back to the JavaScript and execute some function based on this result. This would all happen "behind-the-scenes" without the user leaving the page.
If I understand correctly about what you want, since not all the browsers support socket, this is what you can do:
Have an ajax service call periodically sending requests to the server for update
Once the the parameters from the command line are taken, you can send the result along with an ajax response back to the page, and call the function in the ajax request callback function.
Also, another option, you can use reverse ajax to accomplish this. See Wikipedia about reverse ajax (comet), especially Ajax with long polling.

Categories