Home > front end >  Flask server not accepting values from JS ajax function
Flask server not accepting values from JS ajax function

Time:10-31

Python code -

from flask import Flask
from flask_cors import CORS
import cgi

app = Flask(__name__)
CORS(app)

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__":
  app.run()

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

My javascript function -

function callPythonScript() {
                alert("called_python_script");
                $.ajax({
                    url: "http://127.0.0.1:5000",
                    type: "POST",
                    data:{ 
                        var1: window.location.href,
                    },
                    success: function(response) {
                        console.log(response);
                    },
                    error: function(xhr) {
                        console.log(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()

CodePudding user response:

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' 
        else:
            return 'No value from JS function'
    else:
       # 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

  • Related