Question

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!

Was it helpful?

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.
    });
});

OTHER TIPS

Actually, you don't need to use hidden fields either. ) It may be more simple just to use the post's ID itself - or the rel attribute of upvote/downvote buttons. Like that:

HTML

<div id='post-XXX'> 
   <a href='#' class='upvote_post' rel='XXX'></a> 
   { ... some immensely great post content goes here ... }
</div>

JS

$('.upvote_post').click(function() {
  var post_id = this.getAttribute('rel');
  // or var post_id = $(this).parents('div').getAttr('id').match(/\d+$/);
  $.post(some_url, /* data including post_id */)
}

You can iterate over all buttons and raise the id of each post or they already have ids server side but then you have to tell your script these upon creation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top