1

I am trying to have some javascript that runs a function to update the value of a form input with a reasonably large json dictionary and then I want to get a hold of it on my flask backend. So I have the follow HTML and javascript:

<head>
<!--some info here -->
<script>
        function AddPostData() {
            var data = editor.getValue();
            //this editor.getValue() gets the json string and it is working 
            //as validated by an alert message

            var formInfo = document.forms['json_form'];
            formInfo.elements["json_data"].value = data;
            alert(data)
        }
    </script>
  </head>
  <body>

    <!-- I have the json editing GUI here -->

    <form id="json_form" method="POST" action="/test">
        <input type="hidden" name="json_data" value="" />
        <input type="submit" value="Submit" onclick="AddPostData();">
    </form>

And then here is the python that I have for Flask.

@app.route('/test', methods=['GET', 'POST'])
def test():
    if request.method == 'POST':
        print (request.data)
        the_json=request.data
        #this template simply prints it out and all that I get is b"
        return render_template('testing.html', the_json=the_json)

Any ideas what is going wrong? When I hardcode a string into the data variable I still don't get anything in the request.data field. Well to be exact I get a b followed by one quotation: b"

I suppose it is something wrong in that it isn't actually putting the json into the value field of the input.

clifgray
  • 4,313
  • 11
  • 67
  • 116

2 Answers2

1
the_json = request.form.get('json_data', None)

instead of

 the_json=request.data

will work in the hard coded section (for sure, but I'm not too sure if your java script works/not my area of expertise but it looks ok.).

1478963
  • 1,198
  • 4
  • 11
  • 25
1

Depends on Content-Type In case of

Content-Type: application/json

you can use

request.get_json()

and in case of

Content-Type: application/x-www-form-urlencoded (like what you wanted to do)

you can use

# to get all the items
dict(request.form.items())
# to specific item from post data
request.form.get("json_data")
Adeel
  • 761
  • 7
  • 24