2

The tutorial I am following has this code which works when the page is first loaded, and then it does not. I have read all other questions on "ajax call works the first time only", but could not find a relevant cause. Given that the code works when the page loads, I think there is a binding problem in the jQuery portion that prevents the button to act once it is changed on the first call, but I cannot pinpoint what that is. I also tried visiting the url end-point (REST framework end-point) and every time I refresh the page, the count does update correctly. So, the problem must be somewhere in the front-end since it can clearly find the URL and update the count once but fails to call ajax on subsequent clicks.

<li>
    <a class="like-btn" data-href="{{ obj.get_api_like_url }}" data-likes='{{obj.likes.count}}' href="{{ obj.get_api_like_url }}"> {{obj.likes.count }} | 
    {% for person in obj.likes.all %} 
        {{ person.userprofile.first_name }} 
    {% endfor %}<i class="fab fa-gratipay"></i> </a>
</li> 

In my jQuery code:

$(function(){

$(".like-btn").click(function(e)
{
    e.preventDefault();

    var this_ = $(this);
    var likeUrl = this_.attr("data-href");
    console.log("likeUrl: ", likeUrl);

    var likeCount = parseInt(this_.attr("data-likes")) | 0 ;

    var addLike = likeCount;
    var removeLike = likeCount;

    if (likeUrl)
    {
        $.ajax(
        {
            url: likeUrl,              // likeUrl returns the get_api_like_url of the footer Ex/ likeUrl = {{ project.get_api_like_url }} 
            method: "GET",             // 
            data: {},                  // data to be sent to the server
            success: function(data)
            {
                console.log(data);
                console.log('**********************************');
                console.log("Success!");
                console.log("Likes: ", data.likes_num );
                console.log("liked by: ", data.liked_by );
                console.log("data: ", data)

                if(data.liked)
                {
                    updateText(this_, data.likes_num, "Unlike", data.liked_by);


                }
                else
                {
                    updateText(this_, data.likes_num, "Like", data.liked_by);
                }
                console.log("updated the count button")

            },
            error: function(error)
            {
                console.log("error: ", error)
            }
        })

    }

});

function updateText(btn, newCount, verb, extra){
    btn.text(newCount + " " + verb + " " + extra); // e.g. 2 like or 1 unlike
 }

});

Here is the REST framework code for completeness:

class ProFormaLikeAPI(APIView): #authentication_classes = (authentication.SessionAuthentication,) permission_classes = (permissions.IsAuthenticated,)

def get(self, request, pk=None, format=None):        
    user = self.request.user
    the_pk = pk
    updated = False
    liked = False

    obj = get_object_or_404(Project, pk=the_pk)
    the_url = obj.get_absolute_url()

    if user.is_authenticated():

        if user in obj.likes.all():
            liked = False
            obj.likes.remove(user)

        else:
            liked = True
            obj.likes.add(user)


        likes_num = obj.likes.all().count()

        if likes_num > 1:
            people = 'persons'
        else:
            people = 'person'

        liked_by = [ user.userprofile.first_name for user in obj.likes.all() ]
        updated = True

    data = {'updated': updated,
            'liked': liked,
            'likes_num': likes_num,
            'liked_by': liked_by,
           }

    return Response(data)
EarlyCoder
  • 977
  • 1
  • 12
  • 27

1 Answers1

1

you should prevent all future AJAX requests from being cached (see this discussion:Prevent browser caching of AJAX call result). you can use the cache property (cache: false) in your jQuery code:

     ...
 if (likeUrl)
    {
        $.ajax(
        {
            url: likeUrl,              // likeUrl returns the get_api_like_url of the footer Ex/ likeUrl = {{project.get_api_like_url }} 
            method: "GET",             // 
            data: {},
            cache: false,
            success: function(data)
            {
                console.log(data);
                console.log('**********************************');
       ...

Maybe the problem appeared to you because you use a caching in your Django project (django memcached and ajax requests).