Reputation: 119
I have a while loop that fetches and echos status updates. I am trying to echo a "REPOST" link during my while loop, so that it appends to any status update (sits below it), and when clicked, passes the ID thru to an external .php file. This link is jquery+ajax.
<script type="text/javascript">
$(document).on('click', 'a[id^=repost]', function(){
var thePostID = $(this).prop('id').split('-')[1];
//this now has the id of the $row['id'] we declared earlier.
$.ajax({
url: 'reposthandler.php',
type: 'POST',
data: {'id' : thePostID},
success: function(data){
}
});
});
</script>
<?php
include ('time.php');
$query = "SELECT poster, posterpic, category, type, date, id, follow.beingfollowed
FROM usergen LEFT JOIN follow ON follow.beingfollowed = usergen.poster WHERE
follow.iwannafollow
= '*".$loggedin."' ORDER BY usergen.date DESC ";
$result = mysql_query($query) or die(mysql_error()) ;
$rows = array();
while($row = mysql_fetch_array($result)) {
$row['ago'] = ago($row['date']);
$rows[] = $row;
echo '<br />';
echo '<img src="' . $row['posterpic'] . '" width="40px" height="50px">';
echo '<font color="red" size=2px><i>';
echo '<a>'.$row['poster'].'</a></i></font>';
echo '<br />';
echo $row['category'] . ' for ' . $row['type'] . ' (' . $row['ago'] . ')';
echo '<a href="#" id="repost-',$row['id'],'">REPOST</a>';
echo '<br /><br /><HR size="4" width="auto" color="white">';
}
echo '</div>';
?>
The links are dead and do not link thru to anything. Why is this? Do I need to add something below "success: function(data)"?
Upvotes: 1
Views: 1901
Reputation: 50787
Simply add an element to the loop for the button.
echo '<a href="#" id="repost-',$row['id'],'"> Repost This </a>';
Bind the click function to a static parent element.
$(document).on('click', 'a[id^=repost]', function(){
var thePostID = $(this).prop('id').split('-')[1];
//this now has the id of the $row['id'] we declared earlier.
$.ajax({
url: 'path/to/my/controller.ext?postID='+thePostID,
type: 'POST',
success: function(){
//do whatever with the response.
}
});
});
Now you're being passed the ID of the post you want to repost, and you can handle it however you want in your back end php file.
Upvotes: 1