In this jQuery code, what I’m trying to achieve is that when the logged-in user clicks the follow button, the tweets of the person they are following should appear on the dashboard, and the follow text should change to unfollow.
When I run this code, it does follow the user and saves it to the database, but the follow text does not change to unfollow, and I need to manually refresh the page for the tweets to appear. I want this to happen automatically, with the tweets appearing directly on the screen, and also for the follow text to change to unfollow. What do I need to change or do in this code?
// Follow or unfollow function
document.addEventListener('click', function (event) {
if (event.target.classList.contains('follow-btn')) {
var userId = event.target.getAttribute('data-userid');
var followBtn = event.target;
$.ajax({
type: "POST",
url: '/Home/Follow', // URL to send the follow action
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ UserId: userId }), // UserId property in the FollowUnfollowViewModel model
success: function (response) {
if (response.success) {
// Append the received tweets to the screen
response.tweets.forEach(function (tweet) {
$('#tweets-container').append(
`<div class="tweet" id="tweet-${tweet.Id}">
<time>${new Date(tweet.CreatedAt).toLocaleString()}</time>
<p>
<strong>${tweet.TwitterUser.FirstName} ${tweet.TwitterUser.LastName}</strong>
<span class="text-muted">${tweet.TwitterUser.UserName}</span>
</p>
<p>${tweet.Content}</p>
<div class="tweet-actions">
<i class="fas fa-comment"></i>
<i class="fas fa-retweet"></i>
<i class="fas fa-heart"></i>
</div>
</div>`
);
});
// Change the follow button to unfollow button
followBtn.classList.remove('follow-btn');
followBtn.classList.add('unfollow-btn');
followBtn.textContent = 'Unfollow';
}
},
error: function () {
}
});
}
if (event.target.classList.contains('unfollow-btn')) {
var userId = event.target.getAttribute('data-userid');
var unfollowBtn = event.target;
$.ajax({
type: "POST",
url: '/Home/Unfollow', // URL to send the unfollow action
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ UserId: userId }), // UserId property in the FollowUnfollowViewModel model
success: function (response) {
if (response.success) {
// Remove the tweets of the unfollowed user from the screen
response.tweets.forEach(function (tweet) {
document.getElementById(`tweet-${tweet.Id}`).remove();
});
// Change the unfollow button to follow button
unfollowBtn.classList.remove('unfollow-btn');
unfollowBtn.classList.add('follow-btn');
unfollowBtn.textContent = 'Follow';
}
},
error: function () {
}
});
}
});