0

I am building a simple flask blog and there I am trying to implement like functionality using ajax and jquery. It works without ajax but the page reloads. So I need to use the ajax but when I am using ajax then I got my site redirected to the JSON file which is not expected. Please Help me with this. The code is

        <div class="likers" id = 'result{{ slide.id }}'>
            {% if current_user.has_liked_slide(slide) %}
                <a class="unlike" id="unlike_{{slide.id}}" href="{{ url_for('like_action', slide_id=slide.id, action='unlike') }}">unlike</a>
              {% else %}
                <a class="like" id="like_{{slide.id}}" href="{{ url_for('like_action', slide_id=slide.id, action='like') }}">like</a>
              {% endif %}
              <div id = 'like-count'>
                {{ slide.likes | count }}
              </div>
        </div>

       @app.route('/like/<int:slide_id>/<action>', methods = ['GET', 'POST'])
        @login_required
        def like_action(slide_id, action):
            slide = Slide.query.filter_by(id=slide_id).first_or_404()
            if action == 'like':
                current_user.like_slide(slide)
                db.session.commit()
                return jsonify({'slide_id': slide_id, 'action': action})
            if action == 'unlike':
                current_user.unlike_slide(slide)
                db.session.commit()
                return jsonify({'slide_id': slide_id, 'action': action})

        $(document).ready(function(event) {
        $('.like, .unlike').click(function(){
            var id = this.id;
            var split_id = id.split('_');
            var text = split_id[0];
            var slide_id = split_id[1];



            $.ajax({
                url: '/like/<int:slide_id>/<action>',
                type: 'post',
                data : {slide_id:slide_id, action:text},
                dataType:'html',
                success: function(data){
                    $("like_" + slide_id).html(data);
                    $('unlikes_' + slide_id).html(data);
                }
            });
        });
    });
davidism
  • 121,510
  • 29
  • 395
  • 339
pitambar
  • 1
  • 1

0 Answers0