destinychoice
destinychoice

Reputation: 45

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.

Upvotes: 0

Views: 1059

Answers (1)

abigperson
abigperson

Reputation: 5362

$(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 (e.g. 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. e.g. <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()

Upvotes: 1

Related Questions