0

I need to pass values from my JS code to my Flask code. I am creating a JSON in my JS code and I used AJAX to send it via POST method to my Flask :

$("#btnSubmitRejetRefModele").click(function() {
    var movies = {
        'title': 'SPY',
        'release_date': '12/02'
    }   

    $.ajax({
        url: '/rejets_modeles',
        type: 'POST',
        datax: JSON.stringify(movies),
        dataType: "json"

    }).done(function(result){
        //console.log(result)
    })
}); 

And my python code app.py :

@app.route('/rejets_modeles', methods=["POST","GET"])
def rejets_modeles():
   if request.method == 'POST':
    datax = {}
    datax = request.get_json()

    print("--------------")
    print(datax)

And the result of this in my Terminal :

-------------- None

How can I get my datax printed in my python code ? Thank you

userHG
  • 567
  • 4
  • 29

2 Answers2

2

JS sent it as form data so try print(request.form)

Nick Bond
  • 171
  • 8
  • Yes you're right. I get this : ImmutableMultiDict([('{"title":"SPY","release_date":"12/02"}', '')]), now how can I store just the json into a variable ? – userHG Mar 10 '20 at 10:41
  • Solved. I used : for key in request.form.to_dict(): v = json.loads(key) – userHG Mar 10 '20 at 11:07
0

ImmutableMultiDict([('{"title":"SPY","release_date":"12/02"}', '')]), now how can I store just the json into a variable ?

When an ajax call comes to flask, itll already be a proper python dict thus no need for any extra stuff, thus should be able to use title = request.form['title'] for example.

$.ajax({
    url: '/rejets_modeles',
    type: 'POST',
    datax: movies,
    dataType: "json"

})

without stringify, there's no need to make it into a string and it'll work as expected (probably).

Incoming request data (flask docs), Get the data received in a Flask request