0

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 () {
               
            }
        });
    }
});

7
  • What have you done to debug the response from /Home/Follow? Your description of the problem indicates that if (response.success) { is not true, so doesn't update the tweets/set the button text. Commented Aug 6, 2024 at 15:49
  • @fdomn-m This is a Razor application that I'm developing with C#. I checked the Home/Follow endpoint with breakpoints, and at the end of that method, there is a return Json(new { success = true, tweets }); statement. After this point, the JS continues, and I am facing issues with the JavaScript part. As I mentioned, the record is visible in the database, and I can get the tweets when I manually refresh the page, but I can't get them dynamically." Commented Aug 6, 2024 at 15:54
  • Debug the response (in the javascript) - ie change success: function (response) { to success: function (response) { console.log(response.success, response.Success) one will be undefined and the other (should be) true. Or just console.log(response) and check the output carefully. MVCs return Json will change the case of your properties automatically without you asking unless you tell it not to. Commented Aug 6, 2024 at 16:02
  • When I checked now, yes, it passes through the return Json(new { success = true, tweets }); part, but when I put a debugger in the document.addEventListener('click', function (event) { if (event.target.classList.contains('follow-btn')) { var userId = event.target.getAttribute('data-userid'); var followBtn = event.target;, I saw that it never reaches the part after $.ajax. What could be the reason for this? The libraries are also included in the Layout, and even though it doesn't enter, it still follows in the database, but the tweets only appear after refreshing the page. Commented Aug 6, 2024 at 16:51
  • 1
    "I saw that it never reaches the part after $.ajax" - what part "after $.ajax" are you talking about? There isn't anything after those two AJAX requests, within their respective if statement blocks. Are you talking about it not going into the success callback, perhaps? Then add some logging to the error callback, to see if it branches into that. Commented Aug 7, 2024 at 7:15

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.