Morteza R
Morteza R

Reputation: 2319

Interaction between Javascript and Python

Let's say I have set up a local server by typing python -m SimpleHTTPServer into the command line. In my directory, I have this index.html file which is an html form that receives a name from the user:

<!DOCTYPE html>
<html>
<body>
<p>Enter names in the fields, then click "Submit" to submit the form:</p>
<form id="frm1">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br><br>
<input type="button" onclick="myFunction()" value="Submit">
</form>

<script>
function myFunction() {
    document.getElementById("frm1").submit();
}
</script>

</body>
</html>

In the same directory, I have a Python file that needs to receive the input name from JavaScript. It is supposed to do some sort of analysis on it and maybe returns the new values back later.

I'd like to know how it is possible to pass the textual input over to the Python script.

Upvotes: 2

Views: 5774

Answers (2)

Meng Wang
Meng Wang

Reputation: 277

The basic framework is, HTML and javascript runs in the client, and python (SimpleHTTPServer) runs the in server.

So I think you need a form in your HTML, which will POST the user name to python server program.

Here is an example of python server: http://www.acmesystems.it/python_httpserver And here is example of form : http://www.w3schools.com/html/html_forms.asp . The action attribute must be set correctly for python program to be invoked.

Upvotes: 2

Kit Sunde
Kit Sunde

Reputation: 37055

You wouldn't use SimpleHTTPServer for that. Use flask in the simple case and Django in the larger one. I'm assuming you're rather new to this sort of thing though, so maybe stick with flask for a few weeks, Django can be a bit overwhelming when you start out.

@app.route('/', methods=['POST', 'GET'])
def index():
    if request.method == 'POST':
        # Do stuff
    return render_template('index.html')

Upvotes: 2

Related Questions