Why I can't get callback via AJAX in Flask project?
Question:
This program is based on Flask, it allows user to click ‘LIKE’ button to increase 1 like_count for the post.
with follows, I can not POST the ‘postid’ to ‘/like’ function and can not get callback from it. Terminal shows TypeError:
like() missing 1 required positional argument: ‘postid’.
like.html:
<a href="#" onclick="like(this, {{ post.post_id }});">LIKE({{ post.like_count }})</a>
<script type="text/javascript">
function like(doc, postid){
$.ajax({
url:'{{ url_for('main.like') }}',
data:{postid:postid},
type:'POST',
success:function(callback){
var temp = 'LIKE' + callback;
$(doc).text(temp)
}
});
}
</script>
views.py:
@main.route('/like', methods=['POST'])
@login_required
def like(postid):
post = Post.query.filter_by(post_id=postid).first()
new_count = post.like_count + 1
post.like_count = new_count +1
db.session.add(post)
db.session.commit()
return Response(new_count)
Answers:
You’re posting postid
as form data, not as a url value. Remove the argument from the view signature and get the value from request.form
.
def like():
postid = request.form['postid']
This program is based on Flask, it allows user to click ‘LIKE’ button to increase 1 like_count for the post.
with follows, I can not POST the ‘postid’ to ‘/like’ function and can not get callback from it. Terminal shows TypeError:
like() missing 1 required positional argument: ‘postid’.
like.html:
<a href="#" onclick="like(this, {{ post.post_id }});">LIKE({{ post.like_count }})</a>
<script type="text/javascript">
function like(doc, postid){
$.ajax({
url:'{{ url_for('main.like') }}',
data:{postid:postid},
type:'POST',
success:function(callback){
var temp = 'LIKE' + callback;
$(doc).text(temp)
}
});
}
</script>
views.py:
@main.route('/like', methods=['POST'])
@login_required
def like(postid):
post = Post.query.filter_by(post_id=postid).first()
new_count = post.like_count + 1
post.like_count = new_count +1
db.session.add(post)
db.session.commit()
return Response(new_count)
You’re posting postid
as form data, not as a url value. Remove the argument from the view signature and get the value from request.form
.
def like():
postid = request.form['postid']