ajax post data in flask view
ajax, flask, python, python-2.7
Solution
You are setting the content type to `application/json` but are sending `application/x-www-form-urlencoded` data instead.
Set the correct content type:
$.ajax({
url: '/share',
type: 'post',
contentType: "application/x-www-form-urlencoded",
data: $('#share-form').serialize(),
or better still, leave it at the default by omitting the `contentType` key altogether.
Problem
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) ``` The 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 somebody tell me how to fix this ?