0

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.

1 Answer 1

1

$(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()

Sign up to request clarification or add additional context in comments.

2 Comments

It's never possible to make 2 requests? with the approach I first tried
It's definitely possible to make 2 requests, but once you make a GET or POST request (e.g. submit a form or tell the browser to go to a new page) then any outstanding XHR request (e.g. AJAX) has no place to return to.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.