My page displays posts stored in my database and pairs a like/dislike button to each post. I am trying to make it so that when a user clicks like or dislike, the value is sent to my database for later recollection.
I have a complex loop that I hope to explain: On page load, an ajax call is made to an external php file to fetch data from my database. The result is an object array which holds "postID":value. Inside a for loop, I am storing the value inside var postID for easy access. I'm obviously going about this wrong because the code does execute, but only sends the value and postID of the last occurrence in the loop no matter which pair of buttons I press: If I have 11 posts in my database and I press "like" on post 3 it will store the value 'like' but for post 11. If I press dislike on post 7 it will store the value 'dislike' but for post 11.
So the question is, how do I fix this so when I press like or dislike for post x, it will store the value for that same post and not the last post in my database?
The array looks like this:
{"s":0,"d":[{"postID":"1"},{"postID":"2"},{""postID":"3"},{""postID":"4"},{""postID":"5"},{""postID":"6"},{""postID":"7"},{""postID":"8"},{""postID":"9"},{""postID":"10"},{""postID":"11"}]}
The post divs are the following format:
<div id="post_#"> //# representing the postID in the database
<div id="like_#"></div> //# repesenting the postID in the database
<div id="dislike_#"></div> //# representing the postID in the database
</div>
My jQuery (includes only the like button):
$(document).ready(function() {
$.ajax({
url: 'postID.php', //fetch the above array
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (post) {
if (post.s == 0) {
//Loop through returned data array using: post.d
for (var key in post.d) {
var obj = post.d[key];
for (var prop in obj) {
var postID = obj[prop];
//When like button is clicked do this
$('#like_' + postID).click(function() {
// Declare variables
var value = '1';
// Send values to database
$.ajax({
url: 'check.php', //check.php receives the values sent to it and stores them in the database
type: 'POST',
data: 'postID=' + postID + '&value=' + value,
success: function(result) {
$('#Message_'+ contestID).html('').html(result).prependTo('#post_' + postID);
}
});
});
}
}
}
}
});
});
So again, my problem is that the second ajax loop is only sending the last instance of var postID instead of sending the postID of the post that was actually clicked.
Any ideas?