2

I would like to pass data from a javascript to a python script called test.py, when the button is clicked.

The web page contains the following script:

<script>
$(document).ready(function(){
  $("button").click(function(){
    $.post("/cgi-bin/test.py",
   { name: "Zara" };
    });
  });
});
</script>

<button type="submit">Run</button>

Here is the test.py that runs in the same server of the web page:

#!/usr/python
print('Content-Type: text/html; charset=utf-8\n')
import sys
file = open('/var/www/cgi-bin/temp.txt','w')
file.write(sys.argv[1])
file.close()

I expected that the temp.txt contains the name Zara. But temp.txt is empty.

So my question is:

How the python script gets the argument name from javascript? Can I use sys.argv or i need another python library?

2
  • try running the python executable 'c:\python27\python.exe' on windows, with /cgi-bin/test.py as the first argument and the arguments you need to send to the python script as the next arguments. then you should be able to use sys.argv in your py script Commented Mar 9, 2013 at 21:17
  • Thanks, but reading the question again, I think this was not so clear. test.py is a python script that runs in the same server of the web page. I will add test.py in the question. Commented Mar 9, 2013 at 22:15

1 Answer 1

2

JavaScript sends a regular HTTP Post request and the python script can parse it as a regular CGI script:

#!/usr/python
import cgi
print('Content-Type: text/html; charset=utf-8\n')
form = cgi.FieldStorage()

if 'name' in form:
    with open('/var/www/cgi-bin/temp.txt','w') as file:
        file.write(form['name'])
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, but i think instead of sys.argv[1], the command would be form.getvalue('name'), right?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.