I have a very simple HTML page for testing which has a simple dropdown menu:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<select id="mySelect" onchange="copy();">
<option value="">Select a person:</option>
<option value="Value of m1" >m1</option>
<option value="Value of m2" >m2</option>
<option value="Value of m3" >m3</option>
<option value="Value of m4" >m4</option>
</select>
<br>
<br>
<p>The value of your selected choice is: </p>
<div id="label"></div>
function copy()
{
var selected_value = document.getElementById("mySelect").value
document.getElementById("label").innerHTML = selected_value
}
</script>
</body>
</html>
Now I want to transfer the value of the selection into my python script. My python script has a function which uses the passed value as an argument to give a JSON file. I want to pass the value and then run the script to produce my JSON file when I select something. This is just for testing but my final HTML page will have multiple dropdowns similar to this one each one transferring a value to my python which would be used as an argument. Everything is done locally using local host. Any help would be appreciated!
Its a bit tricky.
You have to use a form to send the data to a PHP-Web Server.
Then use shell_exec($command) to run your Python Script with parameters.
Your PHP Script should look like this:
<?php
$input = $_GET['mySelect'];
//sanitize and check the input
$cmd = escapeshellcmd('/usr/custom/test.py -p ' . $input);
//escape the command
$output = shell_exec($cmd);
//run the script
echo $output;
?>
It's very important to sanitize and check your user input otherwise an attacker could easily get acces to your server.
See more: http://php.net/manual/en/function.shell-exec.php
Notes from php.net
This function can return NULL both when an error occurs or the program produces >no output. It is not possible to detect execution failures using this function. >exec() should be used when access to the program exit code is required."
This function is disabled when PHP is running in safe mode.
Related
I am creating a GUI using Python Eel.
In this UI I have a drop down. user will select the value of dropdown and submit and that dropdown value will reflect in Python console.
But I am unable to receive value from JavaScript.
This is my Python code:
from random import randint
import eel
eel.init("web")
# Exposing the random_python function to javascript
#eel.expose
def random_python():
print("Random function running")
return randint(1,100)
#eel.expose
def getList():
lst = ["a","b","c","d"]
return lst
eel.spawn(eel.js_myval()())
eel.start("index.html")
This is my JavaScript:
let lst =document.getElementById("cate")
document.getElementById("submit").addEventListener("click",()=>{
eel.expose(js_myval)// here i am using eel expose
function js_myval(){
return lst.value;
}
})
This is my html:
<select name="meesho_category" id="cate">
<option value="x">x</option>
<option value="x">a</option>
<option value="x">b</option>
</select>
Read these
Pass JavaScript Variable Value to Python with Eel
https://github.com/ChrisKnott/Eel
I'm going to answer your narrow question about passing the dropdown value from JavaScript to Python, and ignore code that isn't related to that question.
First, let's rewrite your JavaScript like this so it focuses on your question:
document.getElementById("btn-submit").addEventListener("click",()=>{submit()}, false);
function submit() {
eel.on_submit(document.getElementById("cate").value)
}
That JavaScript code defines a click handler for the btn-submit button, which will read the value of cate dropdown and send it to Python code.
Next, let's do the same trim down of the Python file:
import eel
eel.init("web")
#eel.expose
def on_submit(cate_dropdown_val):
print(f"cate val submitted: {cate_dropdown_val}")
eel.start("index.html")
This code exposes the on_submit function from Python to JavaScript. You'll notice it's being called in the JavaScript block listed above inside of the submit function.
Lastly, let's look at the HTML:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="eel.js"></script>
</head>
<body>
<select name="meesho_category" id="cate">
<option value="x">x</option>
<option value="a">a</option>
<option value="b">b</option>
</select>
<button id="btn-submit">Submit</button>
</body>
<script type="text/javascript" src="js/app.js"></script>
</html>
This HTML defines the cate dropdown element, a Submit button, and imports the eel.js and custom app.js shown above.
When the application is run, and a user clicks the submit button, the Python console will print out the value of the cate dropdown to the console.
From the other code in your example, it looks like you want to build more stuff. Please open a new question with the additional help you might need.
I'm trying to pass a value of a option in a select from my HTML form to a PHP variable through Javascript
<script type="text/javascript">
function changeDir(ID){
var dir = document.getElementById(ID).value;
//For debuging purposes i've used an alert to show the value of dir on screen
//alert (dir);
//At this point of the function I want to assign the value of "dir" to the variable $folder
}
</script>
there's my .php with html
<SELECT name="course" ID="course" onchange='changeDir("course")' >
<OPTION value="artes>'">artes</OPTION>
<OPTION value="ingles">inglés</OPTION>
</SELECT>
<?php $folder= ...?>
I'm using this with a php upload lib, all working at the same file.
If anyone can explain me how to assign the value of the option to a php var will be great.
Thanks and Regards.
You can choose 2 different ways. First is AJAX, second is to redirect the page and GET the value of the <select> element.
HTML:
<SELECT name="course" ID="course" onchange='changeDir("course")' >
<OPTION value="artes>'">artes</OPTION>
<OPTION value="ingles">inglés</OPTION>
</SELECT>
JAVA:
<script type="text/javascript">
function changeDir(ID){
var dir = $("course").val();
$.post("php_file.php",
{
posted_dir: dir
},
function(data){
$("id_of_result_elemnt").html(data);
});
}
</script
PHP:
<?php
$folder=$_POST['posted_dir'];
echo "This text will be display in the element with id_of_result_elemnt ID";
?>
Other method is redirect
HTML+PHP:
<SELECT name="course" ID="course" onchange='changeDir("course")' >
<OPTION value="artes>'">artes</OPTION>
<OPTION value="ingles">inglés</OPTION>
</SELECT>
<?php if (iset($_GET['folder']))
{$_GET['folder']=$folder;}...?>
JAVA:
<script type="text/javascript">
function changeDir(ID){
var dir = document.getElementById(ID).value;
window.location = "http://example.com/myphp?folder=" + dir;
}
</script>
The fact is that you can't. They both live in different parts of your page. While you can write them in the same file, all PHP code is processed in the server side and Javascript is not able to see anything from the client side.
What you could do is whether pass it as a AJAX request in order to get back some information to show to the user or make the <select> refresh the page when user changes the option by submitting the form, so you don't lose the "state" of your form, and then verify in your php block if there's any option selected.
I'm trying to store the value of the drop-down 'product' in a javaScript variable and then trying to use that variable in Python code in html view of Web2py framework to further create the drop down for the other component.
I tried two different ways, but both of them did not work.
I want to do a query on database using a keyword which is selected from the Product drop-down and hence generating the second drop down.
<script>
function run()
{
var e = document.getElementById('local_product');
var strUser = e.options[e.selectedIndex].text;
document.getElementById('div_release').innerHTML =' <label>Release : </label> {{rows1 = db(db.Builds.Build.like(\"}}strUser%{{\"")).select()}} <select> {{for r1 in rows1:}}<option>{{=r1.Build}}</option> {{pass}}</select>'
or
document.getElementById('div_release').innerHTML =' <label>Release: </label> {{rows2=db.executesql("Select Build from Builds where Build like\"request.vars.prod_tab\"" )}} <select> {{for r1 in rows2:}}<option>{{=r1}}</option> {{pass}}</select>'
}
</script>
<form method="POST" action="" name="product_filter">
<label>Product: </label>
<select id="local_product" onchange="run()" name=prod_tab >
{{ for r in product_list: }}
<option value="{{r}}">
{{=r}}
</option>
{{pass}}
</select>
{{pass}}
<input type="Submit" name=Set Value="Set">
<form>
Python code in web2py views is executed on the server before the page is sent to the browser, so it is not possible to execute any Python code within the browser in response to user actions. Instead, you must send an Ajax request to the server to retrieve additional data to inject in the page. For ideas on how to achieve what you want, see this answer.
So this is what i have in html:
<p><br><form name="edit" method="post">
<div><select name="Edi" id ="Edi" >
<option selected="selected">Select</option>
<option value="1.php">Apple</option>
<option value="1.php">Bannana</option>
<option value="2.php">Carrot</option>
</select>
<input onclick="return Edit();" type="submit" value="Edit"/></div>
</form>
here is the corresponding javascript:
function Edit(){
if(document.forms['edit'].Edi.value == "Select")
{
alert("Please Select Edit Field");
return false;
}
else
{
window.open(Edi.options[Edi.selectedIndex].value);
return true;
}
}
Here is my problem. As you can see both my option Apple, and Bannana open the same php page. I want that. But i also want a variable in PHP that can store Apple/Bannana depending which was chosen in dropdown.
I tried this in PHP and it did not work.
$Table = $_POST['Edi'];
I know i can create a different PHP page for Apple(1.php) and Bannana(3.php). But in my program creating a page will just be duplicated code. (Apple and bannana just decide which table to store in). Also, i might be adding more options in the future, so i dont want to keep copying code.
What i came up with is putting the variable in javascript, but then tranfering to PHP is not possible. So I decided with creating extra layer rather than creating copied pages. (1 selected-shows apple, bananna) (2 selected-shows carrot). I can do this.
But is this the most efficient way of doing this?
You can use PHP's $_GET array to access URL parameters.
For example:
<option value="1.php?table=apple">Apple</option>
<option value="1.php?table=banana">Banana</option>
And your PHP:
$table = $_GET['table'];
If the variable could be missing, you can provide a default value by using PHP's ternary operator:
$table = isset($_GET['table']) ? $_GET['table'] : 'apple';
I have two dropdown menus that read their data from a MySQL database. I use PHP for connecting to database. The second dropdowns should get populated based on the selection on the first dropdown. The process seems as below to me (correct me if I'm wrong):
PHP section connects to MySQL database and populates dropdown1.
user selects a value on dropdown1 and onchange event is called.
within the onchange function (which is Javascript), a query is sent to MySQL database to fetch values of dropdown2 based on the dropdown1 selection (here is PHP again, right?).
dropdown2 gets populated.
I don't know how to use Javascript and PHP together in order to do this task (number 3 above); or maybe this is not the way to do it at all. Please advise!
Here is my code. As you see below, I'm putting a Javascript function within a PHP code which I suppose is wrong. That's where I got stuck!
<php
$sql="SELECT distinct category FROM table1";
$result=mysql_query($sql);
$optionsCat="";
while($row = mysql_fetch_row($result)){
$optionsCat.="<option value=\"$row[0]\">$row[0]</option>";
}
function genSubCat($catID){
$sql="SELECT distinct subcategory FROM table1 where category=".$catID;
$result=mysql_query($sql);
$optionsSubCat="";
while($row = mysql_fetch_row($result)){
$optionsSubCat.="<option value=\"$row[0]\">$row[0]</option>";
}
}
?>
<select name="catDropDown" onChange="genSubCat(this)">
<option value="0">Select category</option>
<?php echo $optionsCat?>
</select>
<select name="subcategoryDropDown">
<option value="0">Select subcategory</option>
<?php echo $optionsSubCat?>
</select>
Here we have a simple page with input on it. Type a word into it and then click off of the input. Ajax will call the myphp.php script and return the same word you typed in below the original division.
test.html:
<!DOCTYPE html>
<html lang="en">
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#faq_search_input").blur(function(){
var faq_search_input = $(this).val();
var dataString = 'keyword='+ faq_search_input;
if(faq_search_input.length>1){
$.ajax({type: "GET", url: "myphp.php", data: dataString,
success: function(server_response) {
document.getElementById("searchresultdata").style.display = "block";
$('#searchresultdata').html(server_response).show();
}
});
}
return false;
});
});
</script>
</head>
<body>
<div class="searchholder">
<input name="query" class="quicksearch" type="text" id="faq_search_input" />
<div id="searchresultdata" class="searchresults" style="display:none;"> </div>
</div>
</body>
</html>
myphp.php:
<?PHP
echo $_GET['keyword'];
?>
I think you should first study yourself about using web based languages. The code that you've provided is completely wrong. You're trying to access PHP code through HTML? I mean come on!
First rule: Server based languages can't communicate with Client based languages.
You have to send requests and get responses and the way you want to do that dropdown thing is to send a request to a PHP code and get relevant data from it. As Trufa said in the comment, you may want to look at jQuery library, but before that I think you need to check AJAX.