ajaxdjangojquery-ajaxq

How to pass django object id to jquery/ajax upon click of a button?


I'm trying to implement a reddit-like voting system using jquery/ajax. How can I pass the object id of each individual Post with the click of the button?

{% for post in posts %}
    <h2>{{ post.title }}</h2>
    {{ post.upvotes }}<button type="submit">Upvote</button>
    {{ post.downvotes }}<button id="downvote" type="submit">Downvote</button>
{% endfor %}

<script>
    # Somehow need to distinguish between upvote/downvote and include object id
    $(?).click(function () {
        var id = id
        $.ajax({
            url: '/ajax/upvote/',
            data: {
                'id': id
            }
        });
    });
</script>

Solution

  • Possible to add the id as an attribute to each button tag with data-id. and to know which type of vote, you may add it as well to a data attribute data-vote

    {% for post in posts %}
        <h2>{{ post.title }}</h2>
        {{ post.upvotes }}<button data-id="{{post.id}}" data-vote="up" class="vote" type="submit">Upvote</button>
        {{ post.downvotes }}<button data-id="{{post.id}}" data-vote="down"  class="vote" id="downvote" type="submit">Downvote</button>
    {% endfor %}
    

    And add an event the class .vote with js:

    <script>
    # Somehow need to distinguish between upvote/downvote and include object id
    $(".vote").click(function () {
        var id = $(this).data("id"),
            vote_type = $(this).data("vote");
        $.ajax({
            url: '/ajax/upvote/',
            data: {
                'id': id,
                'vote_type':vote_type,
            }
        });
    });