Search code examples
phpjavascriptvote

How to get the post id for the javascript Ajax call?


I have a similar to SO clone i am working on for practice. I am in the middle of coding the vote system. I would like that when the upvote/downvote button is clicked, an Ajax call gets sent with the parameters for the processing page holding the post id and the value.

The post is needed to be able to know which post to record on the processing page that the javascript calls

I have a table of posts each with a post id and a votes table with votes with a vote id, so in my votes mapping table I record the topic id along side the post id.

However I cannot work out how to dynamically give a different post id for the Ajax call to each different post? Should I create perhaps a hidden field?

How is this generally done? Thanks a lot!


Solution

  • On Stack Overflow, every post contains <input type="hidden" value="POSTID">. When a vote button is clicked, the code seeks for this input element, and sends an AJAX request, together with this post ID.

    You can have a look at the relevant code, here: http://userscripts.org/scripts/review/125051
    This user script allows all (including non-registered) users to view vote counts on posts. To do so, the post ID and vote buttons have to be located.

    Stripped down to the bare bones (excluding CSS), the code looks like:

    <input type="hidden" value="--post id--">
    <div class="vote upvote"></div>
    <div class="vote downvote"></div>
    
    // Example using jQuery:
    $('.upvote').click(function() {
        var $this = $(this);
        $.get('/vote', {
            postId: $this.siblings('input[type="hidden"]').val(),
            type: $this.hasClass('upvote') ? '+1' : '-1'
        }, function(data) {
            // do something with server's response.
        });
    });