0

I want to pass a dictionary (button_state) from javascript to python using flask and jquery. On the jquery side, I have:

$(".btn#submit").click(function(event){
    newdata = JSON.stringify(buttons_state);
    console.log("submission button POST attempt: " + newdata)

    $.ajax({
        url: '/submission',
        dataType: 'json',
        type: 'post',
        contentType: 'application/json',
        data: newdata,
        processData: false,
        success: function(response){
            console.log(response);
        },
        error: function(error){
            console.log(error);
        }
    });

});

On the server side:

@app.route('/submission', methods=['POST'])
def submission():
    info = request.get_json(silent=False)
    return info

But I am getting an Error 500:

Traceback (most recent call last):
  File "/Users/timrand/anaconda3/lib/python3.7/site- 
packages/flask/app.py", line 2292, in wsgi_app
    response = self.full_dispatch_request()
  File "/Users/timrand/anaconda3/lib/python3.7/site- 
packages/flask/app.py", line 1816, in full_dispatch_request
    return self.finalize_request(rv)
  File "/Users/timrand/anaconda3/lib/python3.7/site- 
packages/flask/app.py", line 1831, in finalize_request
    response = self.make_response(rv)
  File "/Users/timrand/anaconda3/lib/python3.7/site- 
packages/flask/app.py", line 1982, in make_response
    reraise(TypeError, new_error, sys.exc_info()[2])
  File "/Users/timrand/anaconda3/lib/python3.7/site- 
packages/flask/_compat.py", line 34, in reraise
    raise value.with_traceback(tb)
  File "/Users/timrand/anaconda3/lib/python3.7/site- 
packages/flask/app.py", line 1974, in make_response
rv = self.response_class.force_type(rv, request.environ)
  File "/Users/timrand/anaconda3/lib/python3.7/site- 
packages/werkzeug/wrappers.py", line 921, in force_type
response = BaseResponse(*_run_wsgi_app(response, environ))
  File "/Users/timrand/anaconda3/lib/python3.7/site- 
packages/werkzeug/test.py", line 923, in run_wsgi_app
    app_rv = app(environ, start_response)
TypeError: 'dict' object is not callable

The view function did not return a valid response. The return type must be a string, tuple, Response instance, or WSGI callable, but it was a dict. 127.0.0.1 - - [29/Oct/2018 07:53:48] "POST /signUpUser HTTP/1.1" 500 -

It seems that the server code is not correctly retrieving the data or that there is a problem with the way that the data was converted to a string by JSON.stringify. I have read many others with the same problem, and have tried the solutions on stack overflow, but only get Error 400.

Tim
  • 365
  • 2
  • 15
  • If you could show the complete error your flask application is showing then it might be easy to know what actually the problem is ? – Saad Oct 29 '18 at 10:01
  • Have you tried hardcoding the client-side submission to a valid JSON or even pass empty dict (`newdata="{}"`). This could help you determine whether your problem is client- or server side. – zxxc Oct 29 '18 at 10:02
  • `newdata` is a string here, could this be the issue? What about adding `force=True` in `get_json` arguments? – Learning is a mess Oct 29 '18 at 10:59

1 Answers1

0

I tried to send a javascript dictionary to python-flask via ajax, using another approach and it works perfectly. In case the problem is that the server does not find the data (it is most likely), you can take inspiration from the approach that I describe (which seems the simplest in my opinion)

My configuration is different, you can see this discussion or this link for more information.

1. On the HTML side:

Respectively Loading jquery and adding a dynamic path to my site:

<script type=text/javascript src="{{url_for('static', filename='jquery.js') }}"> </script>

<script type=text/javascript>$SCRIPT_ROOT = {{ request.script_root|tojson|safe }}; </script>

2. On the Jquery side:

$(function(){
    $('.btn#submit').bind('click', function(){
        var dict = {};
        dict.key1 = "value1";
        dict.key2 = "value2";

        new_dict = JSON.stringify(dict);

        $.getJSON($SCRIPT_ROOT + '/_submission', {
            dict: new_dict,
        },function(data){
            alert("Data from flask" + data.new_dict_flask);
        });
    });
});

3. On the Flask side:

@app.route('/_submission')
def submission():
    new_dict_flask = request.args.get('dict')
    return jsonify(new_dict_flask=new_dict_flask)
Tobin
  • 2,029
  • 2
  • 11
  • 19