[Flask] flask and jquery/ajax
Corey Boyle
coreybrett at gmail.com
Wed Jan 22 10:34:28 EST 2020
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?
More information about the Flask
mailing list