1

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!

  • 1
    Hey megamind144, first off my compliments on how well you asked this question, being a new user (welcome!). I think one last piece of information could be added to your question: open devtools in your browser (F12), go to the `network` tab and inspect the request made when you click the button. This might even lead to answering the problem yourself (in that case, don't hesitate to answer your own question by posting the solution here). – Axel Köhler Jan 28 '21 at 12:32
  • Hi Axel, thank you for your comment & warm welcome! I tried what you said and here's what I've got: 38 requests but most of them are fonts/images and they are okay. I see 2 js requests which are my js file and jquery(this is why I said they seem like to be being linked properly) and that's all. I don't see and request in XHR(in which I reckon Ajax data should be?) – megamind144 Jan 28 '21 at 14:06
  • That indicates that the request is never fired. Try debugging your code to see what causes this. You can do this by running the code line by line in devtools, or print some values on critical points using `console.log()`. – Axel Köhler Jan 28 '21 at 15:06
  • I've debugged it as well ([see this JSBin](https://jsbin.com/sisixen/3/edit?html,js,console,output)), and it works for me (also sends a request). Did you [include jQuery](https://code.jquery.com/) into your page? Does the console throw any errors when clicking the buttons? – Axel Köhler Jan 28 '21 at 15:16
  • @AxelKöhler Wow thank you for your amazing helps! I tried looking at sources in devtool and found that there is an error in my js file: `Uncaught ReferenceError: $ is not defined` I did include jQuery into my page if I did it correctly putting `` Do you happened to know how to fix this error? again thank you so much for your kindness! – megamind144 Jan 28 '21 at 16:21
  • Now we're getting somewhere! The error you are getting means that $ (jQuery's object name) is not defined at the point in your code where you use it. This is most likely due to the order you defined your jQuery reference and your own code. Make sure jQuery is loaded before you use it. See this post: [Uncaught ReferenceError: $ is not defined?](https://stackoverflow.com/questions/2075337/uncaught-referenceerror-is-not-defined). – Axel Köhler Jan 28 '21 at 17:15
  • 1
    @AxelKöhler So I should have imported jquery before my own js file..! It works perfectly now thank you so much, you literally saved my day :) Although my problem was due to such a tiny detail, the things you've taught me such as how to use devtool were incredibly crucial and will definitely make my life a lot easier! Have a lovely day and stay gold! – megamind144 Jan 28 '21 at 18:41
  • Very nice! Glad I could help, we're all here to learn! Make sure to answer your own question. It'll be helpful for other's with the same problem and reward you with some reputation and a badge. – Axel Köhler Jan 28 '21 at 18:56

1 Answers1

0

So I've found the reason thanks to Axel!

The problem was quite simple, I was importing jQuery after my JS file so my JS file couldn't interpret jQuery language.

I just simply put jQuery script below JS file script and now it works perfectly.

before:

<script type="text/javascript" src="{{ url_for('static', filename='js/like_button.js') }}"></script>
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>

after:

<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/like_button.js') }}"></script>