Using PHP I am retrieving a list of videos. I am using jquery to display the video in an overlay. I have everything working, but the problem is the method of implementation seems a little brute force to me and I am looking for a way to cut out the redundant code.
Basically I get a list of videos from the database and output those using a foreach loop to the screen. I use the ID of the video to make the like link id for each result unique:
<a id=like<?php echo $video['fileID'] ?>" ...
I then have to add the jquery to each iteration of the loop. Its an ajax call that passes the information about the video, the current user, etc. If the current user votes for a video then the jquery ajax function is called and a new vote count is displayed:
//upVote for a discussion
$('#like<?php echo $video['fileID'] ?>').click(function(){
$.ajax({
type:"POST",
url:'/ajax/likeFile.php',
data:"voter=" + <?php echo (isset($_SESSION['user_id']) ? $_SESSION['user_id'] : ''); ?>
+ "&poster=" + <?php echo $video['userID'] ?>
+ "&classID=" + <?php echo $_SESSION['class'] ?>
+ "&lessonID=" + <?php echo $_SESSION['lesson'] ?>
+ "&id=" + <?php echo $video['fileID'] ?>
+ "&type=like",
success: function(data) {
var $response=$(data);
var votes = $response.filter('#voteCount').text();
$('#fileVotes').text(votes);
$('#like').attr('src', '/images/upvoteDisabled.png');
$('#unlike').attr('src', '/images/downvote.png');
}
});
});
Like I said, this is working fine. The problem is that I would like to cut down on repeating the jquery over and over for each link. Is there a way to call this and just have the item that gets selected pass its current loop iteration variables instead of having create a jquery function for each link?
This is a really convoluted question I know. Thanks in advance to anyone who wants to tackle this.
First, set an HTML5 DOCTYPE so you can take advantage of custom data attributes:
Then have PHP populate your data attributes for each anchor:
Then use a single JQuery click handler: