Reputation: 251
This is my bit of ajax jquery:..........
$(function () {
$(".follow").click(function () {
var element = $(this);
var I = element.attr("id");
var info = 'id=' + I;
$.ajax({
type: "POST",
url: "follow.php",
data: info,
success: function () {
$('.follow' + I).fadeOut(200).hide();
$('.following' + I).fadeIn(200).show();
}
});
return false;
});
});
my html is:
echo "<tr>";
echo '<td>'. $table["username"]. '</td>'.'<td>'.'<a href="#" id="'.$table['id'].'" class="follow">'.'</a>' . '<a href="#" id="'.$table['id'].'" class="following" style="display:none">'.'</a>' . '</td>';
echo "<tr>";
(which is in a while loop)
On success, I'm trying to fade out the follow button (with its ID) and replace it with a following button with the same ID - However when using (+ I) it doesn't seem to be working?
Where am I going wrong?
Upvotes: 2
Views: 105
Reputation: 20159
It would help if you posted some HTML along with your code for us to get an idea what this should work on.
Anyhow, from what I see in your code, I think it looks something like this:
It seems like my deduced markup was right, your markup boils down to:
<a class="follow" id="foobar">Follow</a>
<a class="following" id="foobar">Following</a>
If you would want to select the element with class .following
and ID foobar
, you'd write $('#foobar.following')
or $('.following#foobar')
. So your code would have to be adjusted to:
$('.follow#' + I).fadeOut(200).hide();
$('.following#' + I).fadeIn(200).show();
However, there is a more fundamental problem with this: IDs uniquely identify an element, which means that you cannot have two elements with the same ID on the same page. The HTML above is invalid and the selectors are overqualified with the class selector. A better solution would be to use a data-
attribute to identify which user the follow/following element belongs to:
<a class="follow" data-userid="foobar">Follow</a>
<a class="following" data-userid="foobar">Following</a>
You'd then store the data attribute instead of the ID:
var I = element.data("userid");
and select using the data attribute:
$('.follow[data-userid=' + I + ']').fadeOut(200).hide();
$('.following[data-userid=' + I + ']').fadeIn(200).show();
As noted before, you don't actually need to select the .follow
element any more. Just use the element
!
element.fadeOut(200).hide();
$('.following[data-userid=' + I + ']').fadeIn(200).show();
Upvotes: 4