0

I am developing a web application for study purposes and trying to learn as I go. The functionality I am trying to implement is a like/unlike button with no page refresh. I've followed a few guides and tried to understand Ajax as best as possible. However on clicking the like button the page is redirected to a blank page with 'Success'. I know I'm missing something quite basic but after a few hours find myself unable to resolve the issue:

View

@app.route('/like/<int:album_id>/<action>')
def like_action(album_id, action):
    album = Album.query.filter_by(id=album_id).first_or_404()
    likeunlike = action
    if likeunlike == 'like':
        current_user.like_album(album)
        db.session.commit()
        return "success", 200
    if likeunlike == 'unlike':
        current_user.unlike_album(album)
        db.session.commit()
        return "success", 200

album.html

{% if current_user.is_authenticated %}
        {% if current_user.has_liked_album(album) %}
                <a class="like-button unlike" id="unlike_{{ album.id }}" href="{{ url_for('like_action', album_id=album.id, action='unlike') }}"><i class="fas fa-heart wax"></i></a>
        {% else %}
                <a class="like-button like" id="like_{{ album.id }}" href="{{ url_for('like_action', album_id=album.id, action='like') }}"><i class="far fa-heart wax"></i></a>
        {% endif %}
{% endif %}

JS

$(document).ready(function () {

        // like and unlike click
        $(".like, .unlike").click(function () {
            var id = this.id;   // Getting Button id
            var split_id = id.split("_");

            var text = split_id[0];
            var album_id1 = split_id[1];  // albumid



            // AJAX Request
            $.ajax({
                url: '/like',
                type: 'post',
                data: { album_id: album_id1, likeunlike: text },
                dataType: 'json',
                success: function (data) {
                    var like = data['like'];
                    var unlike = data['unlike'];

                    $("#like_" + album_id).json(data);        // setting likes
                    $("#unlike_" + album_id).json(data);    // setting unlikes


                }

            });

        });

    });

1 Answers1

0

I think you have to stop acting the like, unlike links as a link. You can to do that using event.preventDefault(). More info here: preventDefault() on an <a> tag

Levente Gabos
  • 350
  • 1
  • 5
  • thanks - this got me much closer. On click the page does not reload and it successfully posts. Unfortunately the new button doesn't show up e.g. on clicking like, the like button will disappear but the unlike doesn't show – David Kelly Oct 04 '19 at 14:10