4

I am new at Stackoverflow and this is my first question.

I am making my first blog site, and want a like button, like facebook.

2 problems with my like button.

  1. It wont update like counts in articles with same data-id. I was only avaible to update (this) article-link

  2. When an user likes/dislikes an article, should be able to unlike without refreshing page. It is because it wont check if there is data in database without refreshing page. How can i do that without refresh?

Controller:

        public string LikeThis(int id)
    {
        Article art = DB.Articles.FirstOrDefault(x => x.ID == id);
        if (User.Identity.IsAuthenticated || Session["Username"] != null)
        {
            var Username = User.Identity.Name;
            Member m = DB.Members.FirstOrDefault(x => x.Username == Username);
            art.Likes++;
            Like like = new Like();
            like.ArticleID = id;
            like.UserID = m.ID;
            like.LikedDate = DateTime.Now;
            like.Liked = true;
            DB.Likes.Add(like);
            DB.SaveChanges();

        }

        return art.Likes.ToString();
    }
    public string UnlikeThis(int id)
    {
        Article art = DB.Articles.FirstOrDefault(x => x.ID == id);
        if (User.Identity.IsAuthenticated || Session["Username"] != null)
        {
            var username = User.Identity.Name;
            Member m = DB.Members.FirstOrDefault(x => x.Username == username);
            Like l = DB.Likes.FirstOrDefault(x => x.ArticleID == id && x.UserID == m.ID);
            art.Likes--;
            DB.Likes.Remove(l);
            DB.SaveChanges();

        }
        return art.Likes.ToString();
    }

View:

                        <li>@{ 
                        int userid = Convert.ToInt32(Session["ID"]);

                        if (!User.Identity.IsAuthenticated)
                        {
                            <i class="fa fa-heart-o fa-lg"></i><span>(@art.Likes)</span> 
                        }
                        else if (art.Likes1.Any(x => x.UserID == userid && x.ArticleID == art.ID) || Ajax.ViewBag.Liked == true)
                        {
                            <a href="javascript:void(0)" class="unlike" data-id="@art.ID"><i class="fa fa-heart fa-lg text-danger"></i><span>(@art.Likes)u</span></a>
                        }
                        else
                        {
                            <a href="javascript:void(0)" class="like" data-id="@art.ID"><i class="fa fa-heart-o fa-lg"></i><span>(@art.Likes)l</span></a>
                        }
                        }
                    </li>

Ajax:

        $(document).ready(function () {
        //LIKE
        $("a.like").click(function () {
            var id = $(this).data("id");
            var link = "/Article/LikeThis/" + id;
            var a = $(this);
            $.ajax({
                type: "GET",
                url: link,
                success: function (result) {
                    a.html('<i class="fa fa-heart fa-lg text-danger"></i> (' + result + ')').removeClass("like").addClass("unlike");
                }
            });
        });
        //UNLIKE
        $("a.unlike").click(function () {
            var id = $(this).data("id");
            var link = "/Article/UnlikeThis/" + id;
            var a = $(this);
            $.ajax({
                type: "GET",
                url: link,
                success: function (result) {
                    a.html('<i class="fa fa-heart fa-lg text-danger"></i> (' + result + ')');
                }
            });
        });

    });

I don't hope that i missed anything. Hope u guys can help.

tereško
  • 58,060
  • 25
  • 98
  • 150
Muhaki
  • 140
  • 3
  • 15
  • so what happens now on click like/unlike button ? any errors in console ? – Arun Raj Jan 28 '16 at 12:36
  • How do you prevent me from pressing unlike/like 100 times? – Hrvoje Hudo Jan 28 '16 at 12:42
  • Lets say that i didnt like the post. When i hit like, it works. But when i hit the same button which should be "unlike", it contains an error – Muhaki Jan 28 '16 at 12:43
  • U can like and unlike 100 times. It will only create, and delete the same field in my database. It wont create double field or anything. – Muhaki Jan 28 '16 at 12:44

2 Answers2

3

The problem is, you registered the click event on the "like" and "unlike" css classes on the document ready event. So it will work for the elements present in DOM at that time. In your success handler of the ajax call, you are resetting the anchor tag html to some new markup and the already registered click event code won't work with this.

What you should do is, use jQuery on event delegation to register your click event. It will work for current and future elements(dynamically injected to DOM).

So change your code from

$("a.like").click(function () {
    //do the ajax call
});

to

$(document).on("click","a.like",function () {
   //do the ajax call
});

and it should work.

Another suggestion is, You can use the same code for both the ajax calls if you keep a data attribute in your markup to determine whether user already liked or not and the target url for each so the markup along with jQuery multiple selectors( both the css classes). Also, you should not try to hardcode the url to your action methods in your js code. Instead you should use the Url.Action helper methods as shown in this post

Community
  • 1
  • 1
Shyju
  • 214,206
  • 104
  • 411
  • 497
  • Thanks! That works perfect. Only the 1. one is remaining. When i hit like, how can i update articles with the same data-id at the same time? – Muhaki Jan 28 '16 at 16:45
  • Fixed it. Uploaded down below. – Muhaki Jan 28 '16 at 17:21
  • For performance you would be better putting an id on the closest parent element that is not updated by the ajax call as so: `$("#id-of-parent").on("click", "a.like", function (){ ... });` – Ruskin Oct 21 '16 at 12:33
0

I just fixed the 1. question. If you have same article in a page, then it will have same like button which will contain same id.

I am able to update it with multipe attributefilter. My final code is like this:

        //LIKE
        $(document).on("click", "a.like", function () {
            var id = $(this).data("id");
            var link = "/Article/LikeThis/" + id;
            //Choose all a tags with this class and this ID
            var a = $("a[class$='like'][data-id$='"+id+"']");
            $.ajax({
                type: "GET",
                url: link,
                success: function (result) {
                    a.html('<i class="fa fa-heart fa-lg text-danger"></i> <span>(' + result + ')</span>').removeClass("like").addClass("unlike");
                }
            });
        });

It is now fixed! :)

Muhaki
  • 140
  • 3
  • 15