I have a button that submits a vote to flask. The flask route returns the updated votes count in json. I use javascript fetch to update the innerHTML on the button. However, fetch response receives html tags with json instead of plain json.
form
<form class="d-inline" id="vote_post" action="/post/22" method="post">
<input id="csrf_token" name="csrf_token" type="hidden" value="IjU4OGEyYTNhMjNmZjhmMTllZjhhYjhlYzgyODFiOTM0NTIzNjZjMWYi.ZtEFxg.XTO0k9Ijne-QNcI2sliKLi4s2KM">
<input id="" name="input_id" type="hidden" value="22">
<button class="btn btn-outline-dark btn-sm border border-dark-subtle px-1 py-0" id="vote_post_btn" type="submit" name="submit" value="vote_post" style="font-size: .65rem;">0</button>
</form>
flask route
@bp.route('/post/<int:id>', methods=['GET', 'POST'])
def post(id):
post = db.first_or_404(sa.select(Post).where(Post.id == id))
if request.method == 'POST':
if request.form.get('submit') == 'vote_post':
vote = db.session.execute(sa.select(PostVote).where((PostVote.user_id == current_user.id) & (PostVote.post_id == id))).scalar()
count = post.votes_count()
if vote is None:
vote = PostVote(user_id=current_user.id, post_id=id)
count += 1
db.session.add(vote)
else:
count -= 1
db.session.delete(vote)
db.session.commit()
return jsonify({"votes": f"{count}"})
javascript
let post_form = document.getElementById('vote_post');
function sendVote() {
let postData = new FormData(post_form);
let url = {{ url_for("main.post", id=post.id)|tojson }}
fetch(url, {
method: "POST",
body: postData,
})
.then((res) => res.json())
.then((data) => {
// this console never prints
console.log(data);
voteBtn.innerHTML = data["votes"];
})
.catch(console.error);
}
document.addEventListener('DOMContentLoaded', (event) => {
document.getElementById("vote_post").addEventListener("submit", function(e) {
e.preventDefault() // Cancel the default action
sendVote();
});
});
Console error
SyntaxError: Unexpected token ‘<‘, “<!doctype “… is not valid JSON
Promise.catch
sendVote @ 22:956
(anonymous) @ 22:601