1

I'm trying to send data in a dictionary format from the client side JavaScript to the server back end via AJAX. It is working, however the data received on the Python end is not what I expected.

>>> b'new+class=some_valaue&document+id=1234567'

What I am expecting back is:

{'new class': 'some_value', 'document id': 1234567}

My javascript

    $.ajax({
            url: '/reclassify',
            data: {'new class': 'some_value',
            'document id': 1234567,},
            type: 'POST',
            success: function(response){
                console.log(response);
            },
            error: function(error){
                console.log(error);
            }
        });

My Python/Flask

@app.route('/reclassify', methods=['POST'])
def reclassify():
    data = request.get_data()
    print(data)
    return 'success'

I don't have any if POST statements yet because I'm still trying to figure out how to get the data sent across in the right format.

Ari
  • 5,301
  • 8
  • 46
  • 120
  • 1
    Does calling `JSON.stringify(data)` in the ajax request help? You might also try adding `contentType: 'application/json'` to the request object like in [this post](https://stackoverflow.com/a/11191967/6243352). Then use [this post](https://stackoverflow.com/a/20001283/6243352) on the backend. – ggorlen May 08 '19 at 03:27
  • I tried that before and it came out weird, tried it again and it seemed to work :D – Ari May 08 '19 at 03:29

1 Answers1

1

Python

@app.route('/reclassify', methods=['POST'])
def reclassify():
    if request.method == 'POST':
        data = request.get_json()
        print(data)

    return '', 200

JS

    function updateClassifier(e, id) {
        let newClassData = {
        'new class': 'some_value',
            'document id': 1234567,
        }

    $.ajax({
            url: '/reclassify',
            contentType: "application/json;charset=utf-8",
            data: JSON.stringify({newClassData}),
            dataType: "json",
            type: 'POST',
            success: function(response){
                console.log(response);
            },
            error: function(error){
                console.log(error);
            }
        });
}

Output in python

{'newClassData': {'new class': 'some_value', 'document id': '1234567'}}
Ari
  • 5,301
  • 8
  • 46
  • 120