how to get data from 'ImmutableMultiDict' in flask how to get data from 'ImmutableMultiDict' in flask flask flask

how to get data from 'ImmutableMultiDict' in flask


You don't actually need to get data from an ImmutableMultiDict. There are a couple of errors in what you have that are preventing you from just pulling the response as json data. First off, you have to slightly tweak the parameters of your ajax call. You should add in the call type as a POST. Furthermore, datatype should be spelt as dataType. Your new call should be:

var data = {"name":"John Doe","age":"21"};$.ajax({    type: 'POST',    contentType: 'application/json',    url: '/post/data',    dataType : 'json',    data : JSON.stringify(data),    success : function(result) {      jQuery("#clash").html(result);     },error : function(result){       console.log(result);    }});

The data is now actually being sent as a post request with the json type. On the Flask server, we can now read the data as son information as follows:

@app.route('/post/data',methods=['GET','POST'])def postdata():    jsonData = request.get_json()    print jsonData['name']    print jsonData['age']    return "hello world" #or whatever you want to return

This will print John Doe and 21 successfully.

Let me know if this works for you or if you have any additional questions!

Edit: You can return success to the ajax call from flask as follows:

# include this import at the tombfrom flask import jsonify@app.route('/post/data',methods=['GET','POST'])    def postdata():        ...        return jsonify(success=True, data=jsonData)


I came to this page because I'm trying to send a form with AJAX, and I finally found a solution. And the solution is to skip JSON (hope this will help others on the same search):

$.ajax({    type: "POST",    url: my_url,    data: $("#formID").serialize(), //form containing name and age    success: function(result){        console.log(result);    }});

Then, on the Flask server:

app.route('/my_url', methods = [POST])def some_function():    name = request.form['name']    age = request.form['age']    # do what you want with these variables    return 'You got it right'