How to pass JavaScript Variables to Python in Flask?

In this tutorial, we’ll take a look at how to pass JavaScript variables to a Python variable in Flask.

In JavaScript, variables store data that can be used or edited later on. Usually taken as inputs, these values are often used on the server-side. Using the Python Flask framework and AJAX, we can pass along these JavaScript values to the Python function.

Passing a JavaScript Variable to a Python variable in Flask

We will be covering two components that are necessary to perform this operation.

1. First, we will be forming our HTML page, with a basic input area and JavaScript function to pass the value along.

How to pass JavaScript Variables to Python in Flask

We have an onclick() function that is calling our senduserinfo() JavaScript function. Now, there are a few terms to understand here.

  • getElementByID is a method that returns the values whose id matches the string given in the method. And though we are not passing any value to the JavaScript function, it gets the value.
  • XMLHttpResponse(method/URL) is an AJAX object. It is used in sending data to the webserver. Create an XMLHttpResponse object and pass your value through it.
  • JSON.stringfy is a common JSON method. When passing data to a web server data has to string, and the .stringfy method helps us do that.


2. Now, we come to the flask code. The data has been passed to the python function and now we have to receive it. Remember, we have sent the data in JSON string format and now we have to open it. json.loads, it receives the JSON string and converts it to a Python dictionary.

How to pass JavaScript Variables to Python in Flask?

And, this is how you can pass a JavaScript variable is passed to a Python function using Flask.

You can also refer to my other tutorials –

Leave a Reply

Your email address will not be published.