Skip to content
  • YouTube
  • FaceBook
  • Twitter
  • Instagram

Data Analytics Ireland

Data Analytics and Video Tutorials

  • Home
  • Contact
  • About Us
    • Latest
    • Write for us
    • Learn more information about our website
  • Useful Links
  • Glossary
  • All Categories
  • Faq
  • Livestream
  • Toggle search form
  • Tableau Desktop versus Tableau Server data visualisation
  • How to remove unwanted characters Python Data Cleansing
  • How To Fix TypeError: unhashable type ‘slice’ python dictionaries
  • Regular expressions python Python
  • IndexError: index 2 is out of bounds for axis 0 with size 2 Index Error
  • how to add sine and cosine in python code numpy
  • how to select columns with SQL SQL
  • YouTube channel lists – Tuples Python Tuples

How to Pass a Javascript Variable to Python using JSON

Posted on December 13, 2021August 20, 2022 By admin 5 Comments on How to Pass a Javascript Variable to Python using JSON

Estimated reading time: 4 minutes

So you have an application or website that is capturing data using javascript, and you want to pass this to Python, so you can process it further.

Here using Flask, Python’s package for web development, we will show you how to achieve this, and also explain the JSON output.

Where could this be useful?

(A) You want to pass data to a Python program to run a Machine Learning program you have written.

(B) You want to use Pythons functionality to add the data to a dashboard in real-time.

(C) Another use could be that you are in real-time processing requests on a website, but also want to use Python’s functionality to capture metrics on the data.

So how do we achieve this?

Step 1 – In Python create a Flask application

When you create a new Python file, the first step is to create add your import statements to the top of the file:

import json

from flask import request

from flask import Flask, render_template

app = Flask(__name__)

As can be seen from the above, we bring in the flask package. This is now starting the process of creating a web development site.

Step 2 – Create the web route for telling the programme what the HTML template is called.

@app.route('/')
def index():
return render_template('index.html')

Step 3 – Create the logic that will receive the data from the JSON on the website.

@app.route('/test', methods=['POST'])
def test():
    output = request.get_json()
    print(output) # This is the output that was stored in the JSON within the browser
    print(type(output))
    result = json.loads(output) #this converts the json output to a python dictionary
    print(result) # Printing the new dictionary
    print(type(result))#this shows the json converted as a python dictionary
    return result

In the above we will explain the logic:

/test ===> this is what the page further on the logic will look to send the data entered on the website to.

methods=[‘POST’] ===> This is what it is looking out for when the JSON is been sent.

As can be seen in the function the rest of the code just retrieves the data and processes it.

Step 4 – Create the HTML file that will capture input and process the data to JSON.

So the main part of this program is loading the HTML file, entering the data onto the page and then processing it with javascript and AJAX.

The page looks like this:

The code behind this is as follows:

<html lang="en">

<head>

    <title>Data Analytics Ireland</title></head>
<body>

<P>Post some values to a json file</P>


<label for="fname">First name:</label> <input type="text" id="fname" name="fname">
<label for="lname">Last name:</label><input type="text" id="lname" name="lname">
<button type="submit" onclick='myfunction();'>Click Here to see your data</button>


<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script>
    function myfunction() {

        const firstname = document.getElementById("fname").value;
        const lastname = document.getElementById("lname").value;


        const dict_values = {firstname, lastname} //Pass the javascript variables to a dictionary.
        const s = JSON.stringify(dict_values); // Stringify converts a JavaScript object or value to a JSON string
        console.log(s); // Prints the variables to console window, which are in the JSON format
        window.alert(s)
        $.ajax({
            url:"/test",
            type:"POST",
            contentType: "application/json",
            data: JSON.stringify(s)});

}

</script>



</body>
</html>

This block of code is HTML and runs as follows:

There are two input text boxes that take the data entered.

There is a button that when clicked, runs the function onclick=’myfunction();’

Within this function, the const firstname and const lastname capture the values entered into the boxes using the javascript document.getElementById

We then create a dictionary with those values.

Next, we create a variable that takes the dictionary and converts it into the JSON format.

The section starting with ” $.ajax“, creates the JSON and readies it to be passed to “/test” identified in step3.

STEP 5 – Where does this leave us?

At this point, if the program is run and the data has been entered, and the button is clicked, the data has been captured by the javascript, passed into the dictionary and converted to JSON format.

So what does this all look like when completed?

Data entered:

Printed output:

The data first comes as JSON str and is then converted to a Python dictionary.

After this, you can then start manipulating the data in Python!

Flask, Javascript, JSON, Python Tags:javascript variables, json, pass javascript variable to JSON, pass variable to JSON, python Flask website development

Post navigation

Previous Post: How to use parameters in Python
Next Post: How to show percentage differences between files in Python

Related Posts

  • Python Dictionary Interview Questions Python
  • Tkinter GUI tutorial python – how to clean excel data Python
  • TypeError: ‘list’ object is not an iterator Python
  • How to delete a key from a Python dictionary Python
  • How to Create Multiple XML Files From Excel With Python Python
  • TypeError: the first argument must be callable Python

Comments (5) on “How to Pass a Javascript Variable to Python using JSON”

  1. kshitij says:
    July 20, 2022 at 7:36 pm

    I usually never leave feedback, but thank you so much for this, works like a charm, it is perfect.

    Reply
    1. admin says:
      July 25, 2022 at 10:43 pm

      Thank you for visiting the website and YouTube channel. Your comment is really appreciated.

      Data Analytics Ireland

      Reply
    2. admin says:
      August 20, 2022 at 2:50 pm

      Thank you so much for your kind comment and feedback it is really appreciated.

      Data Analytics Ireland

      Reply
  2. olivier de Ipanema Moreira says:
    April 21, 2022 at 10:25 am

    Extremely helpful Post.

    Being highly allergic to JavaScript there was , at least for me , a lot more than met the eyes. The flask route (@app.route(‘/test’, methods=[‘POST’]) is not the usual html rendering but a cunning method triggered by the JavaScript function to actually operate a variable transfer to python. Bravo.
    From here the variable can either be made global for further python handling or simply stored into a Redis db.

    Thank you very much

    Reply
    1. admin says:
      May 2, 2022 at 8:25 pm

      Hi,

      Thank you so much for taking the time to read the posting, and comment. I have another post coming soon about how to validate the data entered using python, but the data is entered in a HTML input box and passed to python via JSON/ajax.

      Data Analytics Ireland

      Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Select your language!

  • हिंदी
  • Español
  • Português
  • Français
  • Italiano
  • Free ways to Extract Data from Files Livestream
  • IndexError: single positional indexer is out-of-bounds Index Error
  • ValueError: invalid literal for int() with base 10 Value Error
  • python classes class
  • How to sort a Python Dictionary Python
  • How to delete a key from a Python dictionary Python
  • How To Add Values to a Python Dictionary Python
  • TypeError: ‘list’ object is not an iterator Python

Copyright © 2023 Data Analytics Ireland.

Powered by PressBook Premium theme

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Cookie settingsACCEPT
Privacy & Cookies Policy

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these cookies, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may have an effect on your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.
Non-necessary
Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies. It is mandatory to procure user consent prior to running these cookies on your website.
SAVE & ACCEPT