I am encountering an issue where my like button is returning a Json object { liked: true } but it is not functioning correctly with my ajax call in my Django application whenever a user tries to click the

Having trouble creating a like button with an AJAX function in Django. Every time I click on the button, it redirects me to a different page showing a JSON object that returns {liked: true}. Why is this happening? It's been quite challenging for me to diagnose the problem - could it be an issue with my JavaScript or the function in views.py? How can I prevent the page from reloading when users click on the like button? Here's the code snippet for my like function:


def like(request, pk, c_slug=None):
    user = request.user
    if request.POST.get("operation") == "like_submit" and is_ajax(request=request):
               liked=get_object_or_404(Like,pk=pk)
    product = Product.objects.get(pk=pk, slug=c_slug)
    liked= False
    like = Like.objects.filter(user_like=user, product=product)
    if like:
        like.delete()
    else:
        liked = True
        Like.objects.create(user_like=user, product=product)
        resp = {
        'liked':liked,
         }
        response = json.dumps(resp)
        return HttpResponse(response,content_type = "application/json")

model.py

class Like(models.Model):
    user_like = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='user_likes', on_delete=models.CASCADE)
    product = models.ForeignKey(Product, related_name='user_likes', on_delete=models.CASCADE)
    like_date = models.DateTimeField(auto_now=True)

This is my script for the AJAX call

<script>
    $(".like").click(function (e) {
    var id = this.id;
    var href = $('.like').find('a').attr('href');
    e.preventDefault();

    $.ajax({
        url: href,
        data: 
        {'liked': $(this).attr('name'),
        'operation':'like_submit',
        'csrfmiddlewaretoken': '{{ csrf_token }}'},
        success: function(response){
          if(response.liked){
            $('#likebtn' + id).html("Unlike");
            $('#likebtn' + id).css("color", "gray")
          }
          else{
            $('#likebtn' + id).html("Like");
            $('#likebtn' + id).css("color", "blue")
          }
        }
      })
});
</script>

my HTML

{% if product in liked %}
<a href='{% url "shop:like" product.id product.slug %}' id="likebtn{{ product.id }}"  class="flexitems-center space-x-2">
<div class="p-2 rounded-full text-black lg:bg-gray-10">
  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="blue" width="22"height="22" class="dark:text-gray-100">
     <path d="M2 10.5a1.5 1.5 0 113 0v6a1.5 1.5 0 01-3 0v-6zM6 10.333v5.43a2 2 0 001.106 1.79l.05.025A4 4 0 008.943 18h5.416a2 2 0 001.962-1.608l1.2-6A2 2 0 0015.56 8H12V4a2 2 0 00-2-2 1 1 0 00-1 1v.667a4 4 0 01-.8 2.4L6.8 7.933a4 4 0 00-.8 2.4z" />
     </svg>
         </div>
              <div >Unlike</div></a>
    {% else %}
  <a href='{% url "shop:like" product.id product.slug %}' id="likebtn{{ product.id }}"  class="flex items-center space-x-2">
    <div class="p-2 rounded-full text-black lg:bg-gray-10">
  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" width="22" height="22" class="dark:text-gray-100">
<path d="M2 10.5a1.5 1.5 0 113 0v6a1.5 1.5 0 01-3 0v-6zM6 10.333v5.43a2 2 0 001.106 1.79l.05.025A4 4 0 008.943 18h5.416a2 2 0 001.962-1.608l1.2-6A2 2 0 0015.56 8H12V4a2 2 0 00-2-2 1 1 0 00-1 1v.667a4 4 0 01-.8 2.4L6.8 7.933a4 4 0 00-.8 2.4z" />
  </svg>
   </div>
      <div >Like</div>
        </a>
   {% endif %}

Answer №1

Your website seems to be missing a proper like button feature, as it appears that the links provided only redirect users to specific URLs instead of triggering any action. In addition, none of your elements are assigned the 'like' class, which means that your JQuery AJAX code is not being activated by any element on the page.

To resolve this issue, I recommend implementing a real <button> HTML element and assigning it the 'like' class. This should enable the functionality you intended for users to like content on your site.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Verifying the presence of an image via its URL may not be functional across all browsers

Hey folks, I'm working on a project that involves displaying an image along with other fields in a loop where the image source changes with each iteration. I also need to check if the image exists and set a default source if it doesn't. The code ...

The autofocus feature does not function properly in an input tag that is not located within a form element

Is there a way to set the autofocus property in an input element that is not part of a form? I have tried adding the "autofocus" attribute to the input tag but it doesn't seem to be working. <div> //I have added the autofocus property her ...

Retrieving the value of a child in JSON

I have encountered this JSON structure and I am interested in extracting the value of "resource_uri" which is "/api/v1/client/2/". My implementation revolves around Backbone/javascript. Unfortunately, using json['resource_uri'] does not produce ...

Creating an illustration with HTML5 from an image

Is it possible to draw on an image by placing a canvas on top of it? I am familiar with drawing on a canvas, but I am facing an issue where clicking on the image does not trigger the canvas for drawing. How can I resolve this? This is how my HTML looks: ...

Organizing information in local storage using an array and converting it to a string

After storing user inputs (Worker's name, Car Vin, Start time and End time) in the local storage, you want to sort the employees' names in alphabetical order. The question is where should the code be placed and how should it be written? // Car C ...

Is it possible for a user to change the data stored in sessionStorage variables?

Incorporating client-side JavaScript into my project to save certain variables using Web Storage - specifically, the sessionStorage. However, uncertainty exists regarding whether a user holds the capability to alter these variable values. If this is indee ...

What is the most effective method to prevent the auto-complete drop-down from repeating the same value multiple times?

My search form utilizes AJAX to query the database for similar results as the user types, displaying them in a datalist. However, I encountered an issue where it would keep appending matches that had already been found. For example: User types: "d" Datali ...

Unable to connect to React Node Socket.IO application from any source other than localhost using IPv4 and NGROK

I recently followed a tutorial on creating a simple React app/Node with Socket.IO. The tutorial worked perfectly, so I decided to test it with two other devices: One PC on the same wifi network (via IPv4 - 192.168.1.8:3000) A mobile device using Ngrok tun ...

Steps for creating a link click animation with code are as follows:

How can I create a link click animation that triggers when the page is loaded? (function () { var index = 0; var boxes = $('.box1, .box2, .box3, .box4, .box5, .box6'); function start() { boxes.eq(index).addClass('animat ...

The isset function in PHP fails to operate effectively on websites utilizing AJAX

Here is my header.php page that contains links to some pages. I am using AJAX to develop my site. <li><a href="log.php" class="ajaxtrigger">Login</a></li> <li><a href="change_pass.php" class="ajaxtrigger" >Change Passwo ...

Is the parent node of the input element the input element itself?

When working with a DOM object obj of type <input>, I encountered an issue where attempting to obtain its parent node using obj.parentNode resulted in the same obj being returned. Is this behavior specific to <input> objects? What other types o ...

Tell webpack to exclude a specific import

Currently, I am in the process of developing a desktop application using ElectronJS and ReactJS. To bundle the renderer process that utilizes JSX, I have opted to use webpack. An issue arises when attempting to import anything from electron into the rend ...

Automatically showcase images from a directory upon webpage loading

Is there a way to modify my code so that the images from the first directory are displayed on the page when it loads, instead of waiting for a menu option to be clicked? The page looks empty until a menu option is selected, and I would like the images to s ...

Button inside table cell not showing Bootstrap tooltip

I've implemented a feature where each row in a table has a button that triggers a pop-up modal when clicked. I want these buttons to display tooltips when hovered over and when focused. Below is an example of the HTML structure: <link hr ...

Connect the dxSelectBox to the button click event

Currently, I am working with the DevExtreme MVVM architecture. In my specific situation, I am trying to bind a dxSelectBox (combo box) upon a button click event. Here is the HTML CODE snippet: <div data-bind="dxButton:{onClick:display,text:'Click ...

Enhance your UI experience with a beautifully styled button using Material-

I was using a Material UI button with a purple background. <Button component={Link} to={link} style={{ background: '#6c74cc', borderRadius: 3, border: 0, color: 'white', heig ...

Synchronize chat messages automatically with the scrolling window using AJAX technology

Original Content Scrolling Overflowed DIVs with JavaScript In my AJAX chat application, messages are displayed in a div with overflow: auto, enabling the scroll bar when the content exceeds the space. I am looking for a solution that automatically scrol ...

Incorporate JavaScript files into your Gruntfile

I utilized a bootstrap-compass project by using the yeoman generator provided in this link: https://www.npmjs.com/package/generator-bootstrap-compass You can view the file structure through the link mentioned above. Now, I am looking for guidance on cor ...

Learn how to trigger the keydown function in VUE programming

I am trying to create a method that will be triggered whenever any key on the keyboard is pressed, regardless of where the focus is. I want to be able to determine which key was pressed in this method. Currently, I have set up an event listener for keydow ...

What are the best practices for sharing context in express and typescript?

Implementing a solution to expose a value to all request handlers using express and typescript is my goal. I am looking for a way to easily "inject" this value from a middleware or an alternative method that allows for simple mocking if needed. Here is th ...