Flask server not accepting values from JS ajax function


Python code –

from flask import Flask
from flask_cors import CORS
import cgi

app = Flask(__name__)

form = cgi.FieldStorage()
var1 = form.getvalue('var1')

@app.route("/", methods=['GET', 'POST'])
def apicall():
  if len(var1)>1:
    return 'received value from JS function'  

if __name__ == "__main__":

error-: TypeError: object of type ‘NoneType’ has no len().- "POST / HTTP/1.1" 500 –

My javascript function –

function callPythonScript() {
                    url: "",
                    type: "POST",
                        var1: window.location.href,
                    success: function(response) {
                    error: function(xhr) {

do i need configure my flask server to accept values from js func,
what i have tried is –

import cgi 
form = cgi.FieldStorage()
var1 = form.getvalue('var1')

PS: this setup works perfectly if i just pass return "Hello world" in python funx apicall()


If you follow the example here, then your python code should be something like

@app.route("/", methods=['GET', 'POST'])
def apicall():
    if request.method == 'POST':
        data = request.get_json() # Get all the data passed in (as JSON)
        var1 = data.get('var1', None)
        if var1 and len(var1)>1:
            return 'received value from JS function' 
            return 'No value from JS function'
       # Code to handle GET 

Note that you’re no longer using form.get.... because you passed in JSON and not form data

Even if you submit a form, it’s usually better to acccess the values as

request.values.get(<var_name>, <default_value>)

The above method allows you to specify a default value in the event <var_name> isn’t available

Answered By – NoCommandLine

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published