skip to Main Content

I´m working on a raspberry pi with debian and I want to execute a python script in a html script with a button. Also I´m using apache2 for the website.

I´m a beginner and tried to do it with jquery and django, but both did not worked.

Some code where I stopped last:

    <form method="post">

    <input type="submit" value="GO" name="GO">
    </form>

    <script language="php">
    if(isset($_POST['GO']))
    {
        shell_exec("/var/www/start.py");
    }
    </script>

Their are no errors, but the code of the script does not get executed. I checked the python script and it´s fine. Also the button works.

3

Answers


  1. Your best bet would be to use the Django framework to achieve that! Just add your script in views.py

    Alternatively you can create the following Ajax:

    <input type = “button” id=”start″ value=”1″>
    <script>
    $(document).ready(function(){
        $("#start").click(function(){
    
            $.ajax({
                method: "GET",
                url: "/home/pi/start.py",
                data: {"place" : value},
                dataType: "text",
                success: function(result){
                    var data=JSON.parse(result);
                    console.log(result);
                }
            });
         });
    </script>
    
    Login or Signup to reply.
  2. Actually the test function is defined, but you need to pay attention to case sensitivity, it’s

    onclick="test()"
    

    instead of

    onClick="test()"
    

    you intend to execute a Python script inside your browser, but it will run on the server. So, inside your test function you will need to send a request via Javascript to the server, using the correct path. This would mean that your browser sends a message to the server, “asking” it to execute the script.

    Login or Signup to reply.
  3. I´ve been working with django and php so depending on what your whole application looks like one might be better than the other.

    To solve this in django you could use the button to redirect to a internal url (for example /buttonclick). There you can juse the related function in views.py to do whatever you want to do in python and then redirect to the page you want to show.
    (Use ajax when you want to dynamically reload parts of your site)

    To solve this in php: Running a Python script from PHP

    If you want to build a bigger application i´d advise you to use django (even though its a bit confusing to start with).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search