Micheal N.D
Micheal N.D

Reputation: 460

Converting like button to Ajax powered like button

I am working on a reverse blog project where users can like and comment. Although I successfully implement the like button to work, But it refreshes the page.

My problem is I am trying to convert it to rather use Ajax to power the button. And to as well uses a flag to decide which button to be shown, like or unlike.

Please I need help or the logic to guide me on converting the button to work on using Ajax Please Note: I use pagination and the like button is on the list view and detail view (CBV). Thank you in advance.

here is my view for the button

enter image description here

here is my model

enter image description here

here is my template rendering

enter image description here

Upvotes: 0

Views: 343

Answers (1)

Hashir
Hashir

Reputation: 400

Set a unique id for each like button if you have multiple like buttons. Bind the click event to JS function in which you will create an ajax call. Pass the ID of your model object (to increment likes count) to your JS function which will be passed in your ajax call to your view. Specify the URL of your view at which your like increment function resides.

Below is the implementation of ajax call on button click in django

https://stackoverflow.com/a/13733855/11979793

UPDATE: Class based view changes for the ajax

In your class-based view function:

Accept the parameters:


        model_id = json.loads(request.POST.get('param_name')) # model_id could be your post ID to increase the likes

instead of render return JSON response for ajax:

        return JsonResponse({
             'like_count': model_to_dict(total_likes), # if you want to display total likes
             'success': True
             })

You can use total likes in success function of ajax to display it in your template.

P.S. import json at start of the file

UPDATE: example class-based view to handle ajax POST request

class myClassView(View):
    template_name='index.html'
    def post(self,request):  # overriding the post method
        myparam = json.loads(request.POST.get('paramFromAjax'))
        # perform your actions here
        # make a dictionary/context say mydic and pass parameters in that
        return JsonResponse({
             'paramToAjax': mydic,
             'success': True
             })

Upvotes: 1

Related Questions