like button in flask using jQuery / json is not working

I’m currently working on a small flask app and trying to make a like button that works without refreshing the page.

Using jQuery seemed to be a way to go so I tried writing some codes, but it doesn’t work.(even from the preventDefault() function)

this is my html structure:

<div class="like_buttons{{ }}">
  {% if and current_user.has_liked_subject(subject) %}
    <a href="#" class="like_button" id="unlike_{{ }}">
      <img src="{{ url_for('static', filename='img/liked.png') }}">
  {% else %}
    <a href="#" class="like_button" id="like_{{ }}">
      <img src="{{ url_for('static', filename='img/unliked.png') }}">
  {% endif %}

and this is my js code to grab user clicking like/unlike button and send data to ‘like’ route, while preventing the page being refreshed:

$(document).ready(function() {

    $(".like_button").on('click', function(event) {


        var request_id = $(this).attr('id').split('_');
        var subject_id = request_id[1];
        var action = request_id[0];

            url : '/like',
            type : 'POST',
            data : { subject_id : subject_id, action : action }



and this is the route that puts like/unlike into database and return data to current page(haven’t written codes to return data yet, please do let me know if you know how to do it)

@app.route('/like', methods=['POST'])
def like():
    subject_id = request.form['subject_id']
    action = request.form['action']
    subject = Subject.query.filter_by(id=subject_id).first_or_404()
    if action == 'like':
    if action == 'unlike':
    return jsonify({'result' : 'success'})
    # return render_template('like_button.html')

It seems like jQuery and js file are being linked to the page properly, but when I press like buttons, the page gets refreshed and nothing happens..

Please kindly let me know what is wrong and what I should do.
Thanks in advance!

95 thoughts on “like button in flask using jQuery / json is not working”

Leave a Comment