0

Lets say I've written a simple html page with a form. The form has 3 input fields that a user fills and presses the submit button. Is it possible to take the values of the 3 input fields from html, use something like ajax in jquery and execute a python script whilst sending those form values to that script as variables?

Everywhere I read about this subject the guides always return the html code in the python script using Flask. Issue is I already have html and all I need is for this form to trigger a python script and just let the user know after pressing the button that the script has been executed. I really would hate to think I need to write my markup in python again!

Is something like this possible?

  • Possible duplicate of [How can I execute a python script from an html button?](https://stackoverflow.com/questions/48552343/how-can-i-execute-a-python-script-from-an-html-button). – brunns Apr 17 '19 at 18:36
  • What is your server-side scripting language you're using for the site? If not Python, why do you specifically need to use Python? It's possible but if you're just using a standard setup (no frameworks) I feel like it would be easier for you to do this with something like a PHP script. – ryan.kom Apr 17 '19 at 18:46
  • not all servers let you run Python script. It has to use CGI. And mostly script has to be in special folder. As for Flask - it doesn't have to send HTML - all depend on you. It can send JSON data which you can use with AJAX. – furas Apr 17 '19 at 18:54

1 Answers1

0

Courtesy of @Zak:

Since you asked for a way to complete this within an HTML page I am answering this. I feel there is no need to mention the severe warnings and implications that would go along with this .. I trust you know the security of your .py script better than I do :-)

I would use the .ajax() function in the jQuery library. This will allow you to call your Python script as long as the script is in the publicly accessible html directory ... That said this is the part where I tell you to heed security precautions ...

<!DOCTYPE html>
<html>
  <head>    
  </head>
  <body>
    <input type="button" id='script' name="scriptbutton" value=" Run Script " onclick="goPython()">

    <script src="http://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>

    <script>
        function goPython(){
            $.ajax({
              url: "MYSCRIPT.py",
             context: document.body
            }).done(function() {
             alert('finished python script');;
            });
        }
    </script>
  </body>
</html>

In addition .. It's worth noting that your script is going to have to have proper permissions for, say, the www-data user to be able to run it ... A chmod, and/or a chown may be necessary.

Alec
  • 8,529
  • 8
  • 37
  • 63