df2 = pd.DataFrame(np.random.randn(5, 10)).to_html()
myPage = """
<html>
<body>
<h2> Website </h2>
<form action="/helloworld" method="get">
<select id = "options">
<option value="">""</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</form>
<button type="button" onclick="showText()">Go!</button>
<div id="show" style="display:none;"></div>
<script>
function showText(){
var value = document.getElementById('options').value;
document.getElementById('show').innerHTML = "you chose " + value;
document.getElementById('show').style.display = "block";
}
</script>
</body>
</html>"""
return HttpResponse(myPage)
This is my code right now. It runs on a local server using Django, and all it does is show a dropdown menu, and when I select an option a block shows up that says "you chose this option". What I want is that when I choose a dropdown option and hit the button, it will return the dataframe I created at the very start. I think this may have to be done using ajax and jquery, but I don't really know anything about that. I've been trying to read up on it but I have no idea how I would implement something that ties together my python and javascript.
Django operates server-side, so any computation you'd like to do with Django (or Python) must be done on the server. The server then passes messages (requests and responses) back and forth to the client (ie. a browser). If you want to return some sort of data to Django, you'll have to use a form to submit the information via POST (a request), or you'll need to use Ajax,JQuery. If Django receives a POST request from the client, it can access data at request.POST['myinteger'] for example, and can perform some computation with that integer, then return another HTTPResponse.
Remember, Django is only able to see and interact with things present on the server. Once sent across the Internet, it has no control. That is where Ajax/JQuery, etc. kick in. They can manipulate data on the client side (the browser downloads JQuery when it loads the page). To send data back and forth, you need to rely on sending requests and responses. This is accurate even when using a RESTful API.
I hope this explanation helps a bit.
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 running in some issues with my code below. I have achieved to create a new element and add it to the Option list. Now a whenever i refresh the page the new element will disappear from the list.I am not familiar how cookies or session works in JavaScript. But how could i store those element and whenever i create a new element to be able to be in the Option list even after refreshing. Sorry for my English , and thank you for the help in advance. My code is below as you can see.
<select name="name" id="name">
<option value="burim" class="someName">burim</option>
<option value="eliot" class="someName">eliot</option>
<option value="saska" class="someName">saska</option>
</select>
<br><br>
<input type="text" id="add">
<input type="submit" name="submit" value="ADD list" id="btn">
<p class="output"></p>
<script>
var btn=document.getElementById("btn");
btn.onclick=function(){
var n =document.getElementById("name");
var list=document.getElementById("add").value;
var listArray={};
var newOption=document.createElement("option");
listArray=n;
newOption.className="someName";
newOption.innerHTML=list;
newOption.value=list;
n.appendChild(newOption);
}
</script>
There is three ( main ) way to store client side data in Javascript.
The cookies are used to store data that is accessible to the server, ex: JWT authentication token.
The other two are Session storage and local storage. I've never learn the difference between the two but here is a good question about it.
In your case, I would suggest using localStorage. It is very easy to use and will be available until clear programmatically or by the user.
You can add data to the localStorage using
window.localStorage.setItem('key', value)
and retreive it using.
window.localStorage.getItem('key')
You should only keep minimum data in the localStorage, don't store your HTML. Store only enough data to rebuild it once you need your information.
Im trying to pass a value from one page for a product to another page for the cart.
I've tried a few different options but haven't managed to come up with any solution.
I'm new to html and javascript so need a simple solution if thats possible so that I can understand.
Product Page
<label for="exampleFormControlSelect1">Example select</label>
<div>
<select class="form-control" id="Selected">
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value='4'>4</option>
<option value='5'>5</option>
</select>
</div>
<button id='btn' type="button" class="btn btn-secondary">Add To Cart</button>
<script type="text/javascript">
var value=0;
function send_selected(){
var selector = document.getElementById('Selected');
var value = selector[selector.selectedIndex].value;
sessionStorage.setItem(value);
}
document.getElementById('btn').addEventListener('click',send_selected);
</script>
Cart page
<script type="text/javascript">
var value = sessionStorage.getItem("value");
document.getElementById('display').innerHTML = value;
</script>
<body>
<div id="display"></div>
</body>
I would need to value from the drop down to be passed to the cart page to work out the value for all the users products selected.
You need to add two arguments to sessionStorage: key and value. Something like this:
sessionStorage.setItem("selectValue", value);
Also, as far as I know if you work with local html files opened like path/cart.html in the browser, the sessionStorage can't help you; it's scope is limited to the page. If you serve them through localhost, you'll be alright.
If this pages have different url, you can do it with query params: https://en.wikipedia.org/wiki/Query_string
By Browser Storage Method :
As mentioned by #Ferenc, the setItem method of session storage takes two parameters.
sessionStorage.setItem("selectedItem","value");
or you can use
sessionStorage["selectedItem"] = "value";
And to retrieve the value anywhere else in the browser you can either use the getItem() method or you can go with the array like value access approach i.e.
var value = sessionStorage["selected"];
But I would suggest you go with localStorage instead of sessionStorage, Because of it's larger scope than the sessionStorage scope.
You can read difference b/w session storage and local storage here.
Note: You can check for errors in your javascript code(Which now occurs when you call the getItem method with a single parameter ) by looking in the browser console.
By Query Parameters:
Well, this is not a recommended method if you are not using any server-side language. i.e. Java, PHP etc.
In this case, you append the query string in url. i.e.
http://www.url.com?value=selected
To Read how to access query parameters by using javascript refer to this question.
It worked for me to add to the 1st HTML file:
where_from = document.getElementById("where_from").value;
sessionStorage.setItem("pass_to_other_form", where_from);
and then to the 2nd HTML file:
var from_other = sessionStorage.getItem("pass_to_other_form");
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.
I am new to PHP and hope someone can help me with this.
I have a page (index.php) where users can select a language.
If no language is selected than the page URL is just index.php which defaults to English.
If they select a language than the page gets reload and the variable ?lang=xy is added to the URL which defines the page language.
E.g. for German the page URL would then be index.php?lang=de .
So far everything works as intended.
Now I have a navbar on the index page that allows to navigate to other pages which are all saved as separate php files (like page1.php, page2.php, page3.php etc.).
How can I manage that if someone has selected a language on the index page and then navigates to another page that the language variable is passed along to all other pages ?
E.g. for German the other pages shoud be page1.php?lang=de, page2.php?lang=de, page3.php?lang=de etc.
I know I can use $_GET["lang"] on each page to fetch the variable but couldn't find a way to pass this on from the index page to other pages using PHP or JavaScript/jQuery, ideally in a way that I can set this more general instead of separately for every single link.
Note:
I am using undordered lists with standard links to create my navbar, e.g.:
<li>Page1</li>
Can someone help me with this ?
Many thanks in advance.
You can use cookies to do so
setcookie(name, value, expire, path, domain, secure, httponly);
i.e.:
setcookie('language', 'german', 60000,"/");
and then check this wherever with
$_COOKIE["language"]
http://php.net/manual/en/features.cookies.php reference
you can use sessions to pass variables to any page,it's more secure than cookies as it's a server side,
example:
After Posting Data:
<?php
session_start();
if(isset($_POST)){
$var_name=$this->db->real_escape_string($_POST['input_name']);
$_SESSION['var1_sess']=true;
$_SESSION['var1_sess']=$var_name;
}
?>
note:session_start() must be in the first line of the file.
If you are using to select languages, just add onchange event to then submit the form to index.php
<form action="index.php">
<select name="lang" onchange="javascript:this.form.submit()">
<option value="en">English</option>
<option value="xy">XY</option>
</select>
</form>
and in the same page
<?php
$lang = $_GET['lang'];
if(empty($lang)){
$lang = "en";
}
?>
Then pass the $lang to where you want to
<li>Page1</li>