Home > Software engineering >  flask not providing results to ajax call
flask not providing results to ajax call

Time:10-30

I am making ajax call to flask function to get data using a token as following

@app.route("/questgen/results", methods = ['POST', 'GET'])
def fetch_results():

    token = request.form.get('token')
    print(token)
    conn = sqlite3.connect("database.db" , timeout=20)
    cur= conn.cursor()
    select_query = '''SELECT processed, output_text 
                    FROM results 
                    WHERE token = token 
                    '''
    cur.execute(select_query)
    records = cur.fetchall()
    processed = ""
    html = ""
    for row in records:
        processed = row[0]
        html = row[1]
    conn.close()
    data = {'processed': processed, 'html' : html}
    

    return redirect(url_for('questgen', data = data))

ajax call is as following

        $.ajax({
            type: "POST",
            url: "/questgen/results",
            data: { token: token },
            datatype: "json",
            success: function (data) {
                if (data.processed == 1) {
                    $('#divresults').html(data.html);
                    $('#divresults').show();
                    hideMyModal();
                    clearInterval(saveInterval);
                }
            }
        });

the complete is a bit lengthy it can be found in this gist the problem is that it returns

TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement.

even though I have tried same flask function as python function by using return data on the same database and it works. I have even tried to get token as function parameter but still it's not working. Can someone help with what am I doing wrong here? Thank you

CodePudding user response:

The jQuery ajax call does not handle redirects automatically. You'll just get a response with a 301 or 302 status code. If you really need to have it redirect, you'll need to check for a 302 status return and make the call again with the changed data. It would be better if you could just do the redirection internally by calling the other function.

CodePudding user response:

Try jsonify to return data

from flask import Flask, jsonify, request #import this 

And then use this to return data

return jsonify({"res": data})

In ajax you will get your data in res

console.log(data.res) // your data
console.log(data.res.processed) // your if condition

Also check whether you need to parse response body or not

  • Related