Ajax post flask data

Here is my view function

@app.route('/share', methods=['GET', 'POST'])
def share():
    form = ShareForm(request.form)
    if request.method == 'POST':
        title = form.title.data
        body = form.body.data
        share_id = form.share_id.data
        print 'form data %s %s %s' % (title, body, share_id)
        if not share_id:
            share = Shares(title, body, 'PUBLISHED', current_user.id)
            db.session.add(share)
            db.session.commit()
            form.share_id.data = share.id
        return jsonify({'status': 204, 'body': {'status': True}})
    else:
        return render_template('share.html', form=form)

Code for ajax post request

<script>
    $(function(){
      $('#share').on('click', function(e){
        e.preventDefault(); // preventing default click action
        $.ajax({
          url: '/share',
          type: 'post',
          contentType: "application/json; charset=utf-8",
          data: $('#share-form').serialize(),
          success: function(){
            console.log('success');
            console.log( $('#share-form').serialize());
          }, error: function(xhr, textStatus, errorThrown) {
            alert(xhr.responseText);
            console.log( $('#share-form').serialize());
          }});
        })
        //return false;
      });
</script>

in the view, when I try to print the request object, I get the following data

print request.data
'title=adsl%3Blsaj%3Blj%3Bl&body=j%3Bas%3Bl%3Bl+&share_id='

But if I try to do

print request.form.get('title', 'None')

I get "None"

Can someone tell me how to fix this?

+3
source share
1 answer

You set the content type application/json, but send data instead application/x-www-form-urlencoded.

Set the correct content type:

$.ajax({
  url: '/share',
  type: 'post',
  contentType: "application/x-www-form-urlencoded",
  data: $('#share-form').serialize(),

or better yet, leave it by default, omitting the key altogether contentType.

+8
source

All Articles