how to get data from 'ImmutableMultiDict' in flask

Issue

I am learning how to use ajax and Flask ,so what I do is I send a ajax request and I receive the data as post request in my python file

My html file contains this code

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

And My python file contains :

@app.route('/post/data',methods=['GET','POST'])
def postdata():
  #do some
  data = str(request.args)
  json_dumps = json.dumps(data)
  return json_dumps

This gives me following data on the page

"ImmutableMultiDict([('{\"name\":\"John Doe\",\"age\":\"21\"}', u'')])"

And this is what my request.query_string looks {%22name%22:%22John%20Doe%22,%22age%22:%2221%22}

So how do I get the name and age. Please correct me If I am wrong anywhere.Thanks in advance.

Solution

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 tomb
from flask import jsonify

@app.route('/post/data',methods=['GET','POST'])
    def postdata():
        ...
        return jsonify(success=True, data=jsonData)

Answered By – Jason Brooks

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