0

i want to send JSON format data in my flask app using AJAX call, when i send it i got "None" in flask.

here is jquery,

$('#form').on('click',function(){
  var text = $('#textField').val();
  var obj = {name:text};
  var myJSON = JSON.stringify(obj);
  $.ajax({
    data : myJSON,
    url: '/process',
    type : 'post',
    contentType: 'application/json',
    dataType : 'json'
  })
})

here is my Flask route,

@app.route('/process',methods=["POST"])
def process():
    data = request.json
    return render_template("form.html",data = data)

in data i got "None".

2 Answers 2

1
  • return render_template is not fruitful as data is being sent via Ajax. It will return the template contents.
  • You can receive the data returned from Flask via done method in Ajax.

I am adding an example code to demonstrate how to handle Ajax submission with JSON data.

app.py:

from flask import Flask, render_template, request, jsonify

app = Flask(__name__)

@app.route('/process',methods=["GET", "POST"])
def process():
    if request.method == 'POST':
        data = request.json
        return jsonify(data)
    return render_template("form.html")

app.run(debug=True)

form.html:

<html>
    <head>
        <title>Form</title>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    </head>
    <body>
        <div id="data"></div>

        <input type="text" id="textField" />
        <button id="demo_btn">Dummy button</button>
        <script>
            $(document).ready(function () {
                $("#demo_btn").on("click", function() {
                    var text = $('#textField').val();
                    var obj = {name:text};
                    var myJSON = JSON.stringify(obj);
                    $.ajax({                        
                        url: '/process',
                        type : 'post',
                        contentType: 'application/json',
                        dataType : 'json',
                        data : myJSON
                    }).done(function(result) {
                        $("#data").html(result["name"]);
                    }).fail(function(jqXHR, textStatus, errorThrown) {
                        console.log("fail: ",textStatus, errorThrown);
                    });
                });
            });
        </script>       
    </body>
</html>

Output:

flask ajax json submission

Reference:

http://api.jquery.com/jquery.ajax/

Sign up to request clarification or add additional context in comments.

3 Comments

after getting data i want to query it in database in SQLalchemy, and passing querying in render_template but using request.json i got "None" in data.
@HamzaAwan, have you tried my example? The textField form data is being sent to Flask in data = request.json. After getting this data you can make database query and return result to Ajax again. Hope it helps. :)
i have tried, it works, but i want to send data through render_template any idea how can i fix it?
0

It looks like JQuery isn't setting the correct header.

If you use the request.get_json() method instead of the request.json property it will get json irrespective of the header.

1 Comment

i also used request.get_json() but same result "None", and i used request.get_json(force = True), i got this error, Bad Request Failed to decode JSON object: Expecting value: line 1 column 1 (char 0)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.