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

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) {

        event.preventDefault();

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

        $.ajax({
            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':
        current_user.like_subject(subject)
        db.session.commit()
    if action == 'unlike':
        current_user.unlike_subject(subject)
        db.session.commit()
    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