简体   繁体   中英

ajax json post request to flask

I am struggling to send a ajax post request but cannot figure out where i am going wrong, i have this form which i submit with js and along with that form i want to send the id of a div:

<script type="text/javascript">
      $(document).ready(function() {
        $('input[type=radio]').on('change', function() {
            $(this).closest("form").submit();
            var poll_id = $(this).closest("div").attr("id");
            var data = {poll_id};
            console.log(JSON.stringify(data));
            $.ajax({
                url: '/poll',
                type: 'POST',
                data: JSON.stringify(data),
                contentType: 'application/json',
                dataType: 'json'
              }, function(data) {
                  console.log(data);
                });
          });
    });
    </script>

and in flask i try to request it with request.get_json() but keep getting error 400, the form and db.commit() works fine:

@app.route('/poll', methods=['GET', 'POST'])
def poll():
    polltodb = pollingresult(request.form['points'])
    session['points_session'] = request.form['points']
    db.session.add(polltodb)
    db.session.commit()
    data = request.get_json()
    print data

but the get_json() fails.

$(this).closest("form").submit(); tells your html page to submit the form. If any javascript after that line even executes you'd be making a separate XHR request (eg 2 requests, the data would never be in the same request using this approach). To accomplish what you're trying to do I'd take a different approach:

  1. Add a hidden element to your form. eg <input type="hidden" name="poll_id" id="myHiddenField">

  2. Update your javascript:

     <script type="text/javascript"> (function(){ $('input[type=radio]').on('change', function () { $('#myHiddenField').val($(this).closest("div").attr("id")); $(this).closest("form").submit(); }); }); </script> 
  3. Then, access the data through the form as you normally would and don't worry about get_json()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM