[Flask] flask and jquery/ajax

onlinejudge95 onlinejudge95 at gmail.com
Tue Jan 28 08:26:16 EST 2020


The reason you are receiving this is because the data you are sending as
json is not valid json.

I tried using your code on https://jsonlint.com/
I receive a pare error. Can you try it with data as
>
> {'1': 1}




On Wed, Jan 22, 2020 at 11:07 PM Gergely Polonkai <gergely at polonkai.eu>
wrote:

> I suspect some CSRF protection mechanism. Do you use such a library? Like
> Flask-WTF-s CSRF extension?
>
> Best,
> Gergely
>
> On Wed, 22 Jan 2020, 16:35 Corey Boyle, <coreybrett at gmail.com> wrote:
>
>> I have a button on a webpage that I would like to trigger a function
>> on the server.
>>
>> Example that works...
>>
>> JS
>>
>> <script>
>> $(function() {
>> $('#customers').on('click', '.markfocus', function() {
>> $.get("{{url_for('sales_ajax.focus_customer')}}", {cpk:
>> $(this).data("cpk")}, function(data) {});
>> });
>>
>> //$(this).hide();
>> return false;
>> });
>>
>> </script>
>>
>> Python3
>>
>> @ajax.route('/focus_customer', methods=GP)
>> def focus_customer():
>> cpk = request.args.get('cpk', 0, type=int)
>> if cpk:
>>   customer = m.Customer.query.get_or_404(cpk)
>>   yadayadayada
>>   db.session.add(customer)
>>   db.session.commit()
>>
>> return jsonify(result='ok')
>>
>> However, I know I shouldn't be using GET to make changes in my
>> database, so I am trying to convert the above into a POST request.
>>
>> I've tried...
>>
>> JS
>>
>> <script>
>> $(function() {
>> $('#customers').on('click', '.markfocus', function() {
>> $.ajax({
>> url:"{{url_for('sales_ajax.focus_customer')}}",
>> type:"POST",
>> data:{ 1:1 },
>> contentType:"application/json; charset=utf-8",
>> dataType:"json",
>> success: function(){}
>> });
>>
>> //$(this).hide();
>> return false;
>> });});
>>
>> </script>
>>
>> Python3
>>
>> @ajax.route('/focus_customer', methods=GP)
>> def focus_customer():
>> print(request.data)
>> print(request.json)
>> return jsonify(result='ok')
>>
>> But, I get a 400 bad request message.
>> If I comment out the "print(request.json)" line, I get "b'1=1'" on the
>> terminal.
>>
>> What am I missing here?
>> _______________________________________________
>> Flask mailing list
>> Flask at python.org
>> https://mail.python.org/mailman/listinfo/flask
>>
> _______________________________________________
> Flask mailing list
> Flask at python.org
> https://mail.python.org/mailman/listinfo/flask
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/flask/attachments/20200128/d0f08497/attachment.html>


More information about the Flask mailing list