Python + Javascript

Kartikeya Rana
3 min readMar 28, 2020

This story guides you to build a simple flask server and integrate it with HTML and Javascript.

HTML and Javascript help in building front end while python language provides backend support.

1. Create a new directory called “python-js”.

2. Inside “python-js” create two sub-directories named “static” and “templates”.

3. Create a python virtual environment inside “python-js”. I usually name it venv. Activate the virtual environment.

4. Install flask and flask_cors using pip command.

pip install flask
pip install flask_cors

5. Create a new python file “app.py” inside “python-js” directory.

The folder directory will look like

python-js project directory

5. Open app.py and paste the following code.

from flask import Flask, request, render_template, jsonify
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

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

# Get data received from javascript
data = request.get_json()

resp = {"message": "Your name is " + data["name"]}
print(data)

return jsonify(resp)

if __name__ == "__main__":
app.run(host='0.0.0.0', debug=True)

The server runs at localhost:5000 port. The get_message() will receive the requests when the page loads.

When the request type is “GET”, the page returns the “index.html” template. And when the request type is “POST”, the function gets the data from webpage and returns the message.

6. Create new file “index.html” inside templates directory and paste the following code into it.

<html>
<
head>
<
script
src="https://code.jquery.com/jquery-3.2.1.js">
</
script>
<!--Adding our server conn javascript file -->
<script type="text/javascript" src="/static/server_conn.js">
</
script>
</
head>
<
body>
<
div>
<
form>
<
label >Response </label>
<
div id="Response"></div><br>
<
input type="text" id="name" placeholder="Enter name"><br><br>
<
input type="button" value="Submit", id="login", onclick="send_button()">
</
form>
</
div>
</
body>
</
html>
index.html

7. Create a new file “server_conn.js” inside static directory and paste the following code into it.

var server = "http://127.0.0.1:5000";
var send_msg = {'name':""};

function update_var()
{
var name = String($("#name").val());
send_msg['name']=name;
console.log("update var")
}

function send_button()
{
var appdir="/";
update_var();
console.log(send_msg)
$.ajax({
type: "POST",
url:server + appdir,
data: JSON.stringify(send_msg),
dataType: 'json',
contentType: 'application/json',
}).done(function(data) {
$('#Response').html(data['message']);
});

}

Function update_var() fetches the data from html input label (id=”name”) and saves it in send_msg variable.

Function send_button() is triggered when the submit button is clicked on the webpage. It calls update_var function and sends a post request to the server using ajax. When the server returns the response, the function updates the value on the web page under <div id=Response>.

8. Go to “python-js” directory and run app.py file

python app.py

9. Go to your browser and type “localhost:5000”. It will show you the webpage. Type your name inside the field and click on submit button. The name will be sent to python server and you will see the response on webpage.

index.html with response from server

--

--

Kartikeya Rana

UCD Alumni | Aspiring Product Manager | Building Three Spoon on Google Play | An AI Developer and a heavy writer | https://www.linkedin.com/in/kartikeyarana10/