Python interaction with browser (Raspberry WebioPi) - javascript

I use a tool called "webiopi" to control a wellness device via a Raspberry pi and a relay board. This tool connect buttons on a webpage with a Python script.
I can read the state (low/high) from the GPIO pins on the buttons i've created.
What i want is to show values from the script in the browser.
(Like ' temperature_measured' or. 'Calculated_time')
Is there a way i can show output from the python script to the webbrowser?
button = webiopi().createMacroButton("macro", "Normaal", "Prog1");
$("#top").append(button)
<div id="content" align="center">
<td>
</td>
{{print here output from script.py}}
<div id="top"></div>
</div>
</div>

You could use PHP to call the script and echo the output to the page. You'll need PHP installed and enabled, and the file must end with .php. If you know the webserver you are using, I can give you some additional help. Also note that the script should print all information it wants on the web page into standard output.
button = webiopi().createMacroButton("macro", "Normaal", "Prog1");
$("#top").append(button)
<div id="content" align="center">
<td>
</td>
<?php exec("python myscript.py", $out); echo $out; ?>
<div id="top"></div>
</div>
</div>

In a this forum [Wpio forum][1]https://groups.google.com/forum/#!topic/webiopi/DreW_74gm0o
gives Pete Dudash the answer to this question, which i copy here
Yes, this is possible. What you’re looking to do is add a callback routine to your javascript. First you execute some action in javascript (either from a button press or a timer) and call a python macro. This time, you specify a call back routine when calling the macro. The call back routine receives data from the macro and then you can do whatever you want with it.
Javascript:
function getPythonResponse() {
// "sendData" is the name of the macro you specify in your script.py
// "[]" is an empty list. If you want to send data for the macro to use, you would include that here
// "handlePythonResponse" is the name of the callback routine that will execute once the python macro is finished
webiopi().callMacro("sendData", [], handlePythonResponse);
}
var handlePythonResponse = function(macro, args, response) {
// "response" is the variable that holds the data from script.py
// Now we can apply those results to the webpage by assigning the value to the "pythonResult" id. This is the element in your HTML where you want to print the info.
$("#pythonResult").text(response);
}
Python:
#webiopi.macro
def sendData():
HTML:
<div id="content" align="center">
<td></td>
<span id="pythonResult">{{print here output from script.py}}</span>
<div id="top"></div>

Related

How I can append "PHP echo" code in html <div>

I am developing a chat between 2 users. I store the messages in a MySQL database and on chat box page I call AJAX each 2 seconds to get new messages.
All works fine with plain text messages but now I need to allow users to send also files.
I append the new messages using:
$("#chat_container").append(`
<div class="message-bubble ${clasa} ">
<div class="message-bubble-inner">
<div class="message-text">${output_response.Result[i].out_Message}</div>
</div>
<div class="clearfix"></div>
</div>
`);
My chat_container is:
<div id = "chat_container" class="message-content-inner">
</div>
${output_response.Result[i].out_Message} is the plain text that I store in mysql databased. For files I am uploading them to server using a php script that returns me the path and then i store the path as a message in database like:
<a href='upload/1619779744.jpg'>Picture</a>
Because of this the user will see that the message is actually a link and when he clicks on it he goes to
https://server/upload/1619779744.jpg and he downloads the picture which is good.
The problem is that I want to add some security to the site and not show direct path to files in link.
For this I implemented this class https://github.com/sujeetkrsingh/Secure-Download-Url
It works good in a separated file using:
<div class="message-text">AWS11 Logo</div>
This will return to user the link https://server.com/download.php?f=2f4df28349d56457b897f2ed3966799735564add3bef41c0 which hides the actual path of the file.
The problem is that if I store in database AWS11 Logo instead of <a href='upload/1619779744.jpg'>Picture</a> the link of the file is
https://server/%3C?php%20echo%20$encrypturl-%3EgetDownloadLink(%27upload/1619779744.jpg%27);%20?%3E which is wrong.
So the question is how I can append HTML + PHP code using jquery append function?
In my chat file I included the class in the beginning of file using <?php require_once("EncryptUrl.php"); $encrypturl=new EncryptUrl(); ?> and I renamed the file from .html to .php

Pass Javascript variable to another page via PHP Post

I am having two php pages:
page 1:
<form class="form-horizontal" role="form" method="post" action="Page2.php">
<button id="place-order" class="btn btn-lg btn-success">Place Order</button>
<div id="ajax-loader" style="display:none;"><img src="images/ajax-loader.gif" /></div>
</form>
<script>
var id = Math.random();
$(document).ready(function() {
$('#place-order').on('click', function() {
$(this).hide();
$('#ajax-loader').show();
});
});
</script>
As on form, it redirects to Page2.php, I want to pass the Javascript variable "id" from Page1 to receive it in Page2.
I have tried using cookies, but need an alternative approach.
I am not understanding the transistion from PHP to JS and vice-versa. Help is appreciated.
Thanks in advance
Dear you can do it very easily with ajax. Ajax has data attribute which helps you pass your data from javascript to another page.
This link will help you a lot
https://api.jquery.com/jquery.ajax/
You can use session storage or cookies.
Example for session storage:
// First web page:
sessionStorage.setItem("myVariable", "myValue");
// Second web page:
var favoriteMovie = sessionStorage.getItem('myVariable');
You could use a query string to pass the value to the next page.
Add an ID to the form
<form class="form-horizontal" role="form" method="post" action="Page2.php" id="order-form">
Update the action of the form to add this query string from our JS variable
var id = Math.random();
$('#order-form').attr('action', 'Page2.php?id=' + id);
Get this variable in PHP (obviously you might wanna do more checks on it)
<? $id = $_GET['id'] ?>
We can now use $id anywhere in our PHP and we'll be using the ID generated from JS. Neat, right? What if we want it in JS again though? Simply add another script tag and echo it there!
<script type="text/javascript">
var id = <? echo $id ?>;
</script>
EDIT: Updated to add a little about how it works as you said you're not too sure about the transition between PHP and JS.
PHP runs on the server. It doesn't know much about the browser, and certainly doesn't know about JS. It runs everything and finishes executing before the web page is displayed. We can pass PHP variables to JS by creating script tags and creating a new javascript variable, echoing the PHP value.
JS (JavaScript) runs in the browser. It doesn't know about anything that happens on the server; all it knows about is the HTML file it is running in (hit CTRL+U to see raw HTML). As JS runs at a completely separate time to PHP there is no easy way to transfer variables (e.g. $phpVar = myJSVar). So, we have to use server methods like POST or GET.
We can create a GET or POST request in 2 main ways:
Using a form
Using an AJAX request
Forms work in the way I've outlined, or you can create a hidden field, set the value you want and then check for that. This involves redirecting to another page.
AJAX (Asynchronous Javascript And Xml) works slightly differently in that the user doesn't have to leave the page for the request to take place. I'll leave it to you to research how to actually program it (jQuery has a nice easy API for it!), but it basically works as a background request - an example would be displaying a loading spinner whilst loading order details from another page.
Hope this helps, let me know if something's not clear!

Accessing Js variable in php on the same page just with a difference of div tag in URL

I have a page say abc.php which displays a list of image names in a table.
When u click on any image name, the page loads an overlay at abc.php#openModal. This new page displays a list of related sensor values which are dependent upon the image name.
How do i get the image name when u click on the link to open the overlay ??
Sample Code:
<html>
<body>
<table>
<tr><td>Image name</td></tr>
<tr><td><a href='#openModal'>Image1</a></td></tr>
</table>
<div id="openModal">
<table>
<tr><td>Sensor value</td></tr>
<?php
$sql="SELECT sensor_value FROM table WHERE imageid='$id'";
$result=mysqli_query($conn,$sql);
if($result){
$row=$result->fetch_assoc();
echo "<tr><td>".$row['sensor_value']."</td></tr>";
}
?>
</table>
You cannot access JS variables from PHP code just because PHP is executed on server and JS - on client. In other words, PHP code ends execution earlier than JS code starts.
In you case you should on click call your JS function, which makes async query to server and displays call result in your modal window.

javascript generating php doens't works

Hello I have an option list in html that is created dynamically by php. I want to take the value of the option list withought subbmiting everything and then call another php function to fill another option list. To be more specific I want the user to first pick a University from a database and then to pick a department of that Universe. I 've created dynamicaly the option list for the Uni's by fetching all Uni's from the database and then find the value by javascript. So in the javascript function I want to write php code in order to fetch all the departments from the university. Eveything works fine until I try to call the php function from the javascript.
signup.php
<form>
<table>
.
.
.
<tr>
<td> Ίδρυμα:</td>
<td><select id="selection" name="selection" onchange="selectDep()" >
<?php include './selectUni.php'; ?>
</select> </td>
<td><span id="orgError" style="display: none;"></span> <td>
</tr>
<tr>
<td> Τμήμα:</td>
<td id="dep" name="dep" ></td>
<td><span id="depError" style="display: none;"></span><td>
</tr>
.
.
</table>
</form>
generateDep.js
function selectDep(){
if(document.getElementById('selection').value === "---")
return;
var value=document.getElementById('selection').value;
alert(value);
document.getElementById('dep').innerHTML=" <?php include './selectDep.php'; selectDep("+value+"); ?> ";
return true;
}
the value at the alert is correct
selectDep.php
<?php
//just trying to make this work for now
function selectDep($value){
echo $value;
}
?>
I cannot understand what I am doing wrong. Everything look fine to me. Can you help me?
First You have to understand that the javascript code executes in web browser but the php code executes in web server.
You can use AJAX to fix your problem.
PHP is a server-side scripting language. It is executed on the server, which means the page has to submit values to the server as a trigger. Javascript and HTML are client-side, which means it's all done in the browser without communicating with the server.
To see this in action, right-click on a PHP page in the browser and select to view source. All you will see is the HTML, you will not be able to view any of the PHP code that generates the page. When PHP executes on the server, the result is client-side code (javascript, HTML and maybe CSS) which is sent to the browser.
The browser wouldn't know what to do with PHP code. If you set the inner HTML of an element to some PHP code in client-side script, it won't get executed and all you will achieve is having the browser render the PHP script exactly as you entered it.
In short, the javascript has to submit the selected value back to the server, before the server-side PHP can work out which departments to send back to the browser.

Using HTML variable in PHP

I'm trying to use the value stored in token in my PHP script to update a database value with SQLite. It wont let me use document.getElementByID....any ideas?
<div id="TokenCount">
<label for="token"><abbr title="Tokens">Tokens</abbr></label>
<input id="token" value="0" />
</div>
<div id="Buttons">
<button id="pay" onClick="pay(10); loadMessage()"><?php $db=sqlite_open("../../logins.db");
$token = document.getElementById('token').value;
sqlite_query($db,"UPDATE Users SET tokens='$token' WHERE user_id='{$_SESSION['user_id']}'");
sqlite_close($db); ?>Pay</button>
</div>
</div>
PHP code is executed server-side, so the website is sent to the client with the result of the PHP code without any PHP found in the source. Because of this HTML tags cannot be used in PHP on a website.
As i said in comments, you can't execute PHP-code(server side code) on client side (in browser).
You should send AJAX query to server, and save this value to mysql on server side.
Javascript(jquery) code:
function loadMessage(){
$.post("setValue.php", {val:document.getElementById('token').value} function( data ) {
alert('success');
});
}
Create new php script for example setValue.php (r use contoller action, or your own staff how you routing pages). Script code:
$token = $_POST['val'];
sqlite_query($db,"UPDATE Users SET tokens='$token' WHERE user_id='{$_SESSION['user_id']}'");
sqlite_close($db);

Categories