Home Like button with Ajax
Reply: 2

Like button with Ajax

JohnWire
1#
JohnWire Published in 2017-12-07 18:02:52Z

I am trying to create a like button with ajax.

This is my architecture:

models.py

class Comentario (models.Model):
    titulo = models.CharField(max_length=50)
    texto = models.CharField(max_length=200)
    autor = models.ForeignKey (Perfil, null=True, blank=True, on_delete=models.CASCADE)
    fecha_publicacion = models.DateTimeField(auto_now_add=True)
    tag = models.ManyToManyField(Tags, blank=True)
    slug = models.SlugField(null=True)
    likes = models.ManyToManyField(Perfil, blank=True, related_name="likes")

    def __str__(self):
        return (self.titulo)

    @property
    def total_likes(self):
        return self.likes.count()

    def save(self, *args, **kwargs):
        self.slug = slugify(self.name)
        super(Comentario, self).save(*args, **kwargs)

views.py

def like(request):
    if request.method == 'POST':
        user = request.user
        slug = request.POST.get('slug', None)
        comentario = get_object_or_404(Comentario, slug=slug)

        if comentario.likes.filter(id=user.id).exists():
            comentario.likes.remove(user)
            message = 'You disliked this'
        else:
            comentario.likes.add(user)
            message = 'You liked this'

    ctx = {'likes_count': comentario.total_likes, 'message': message}
    return HttpResponse(json.dumps(ctx), content_type='application/json')

urls.py

url(r'^like$', login_required(like), name='like'),

html

<input type="button" id="like" name="{{ company_slug }}" value="Like" />
<script>
$('#like').click(function(){
      $.ajax({
               type: "POST",
               url: "{% url 'home:listar' %}",
               data: {'slug': $(this).attr('name'), 'csrfmiddlewaretoken': '{{ csrf_token }}'},
               dataType: "json",
               success: function(response) {
                      alert(response.message);
                      alert(' likes count is now ' + response.likes_count);
            },
                error: function(rs, e) {
                       alert(rs.responseText);
            }
      }); 
})
</script>

When I push the button like it does not do anything.

The console tells me:

Uncaught TypeError: $.ajax is not a function enter code here`  
at HTMLInputElement.<anonymous> (listar:92)  
at HTMLInputElement.dispatch (jquery-3.2.1.slim.min.js:3) 
at HTMLInputElement.q.handle (jquery-3.2.1.slim.min.js:3)

What is the problem?

zvadym
2#
zvadym Reply to 2017-12-08 11:30:56Z

#1

As I can see you use jquery-3.2.1.slim.min.js. This (slim) version excludes ajax module!

https://blog.jquery.com/2017/03/16/jquery-3-2-0-is-out/

Slim build

Sometimes you don’t need ajax, or you prefer to use one of the many standalone libraries that focus on ajax requests. And often it is simpler to use a combination of CSS and class manipulation for all your web animations. Along with the regular version of jQuery that includes the ajax and effects modules, we’ve released a “slim” version that excludes these modules.

#2

You use wrong url as I can see. In your html part it's {% url 'home:listar' %}, given urls.py contains only name='like'

Farrukh
3#
Farrukh Reply to 2017-12-08 11:56:18Z

Put JQuery script before ajax code:

<script src="jquery.js"></script>
$('#like').click(function(){
      $.ajax({
               type: "POST",
               url: "{% url 'home:listar' %}",
               data: {'slug': $(this).attr('name'), 'csrfmiddlewaretoken': '{{ csrf_token }}'},
               dataType: "json",
               success: function(response) {
                      alert(response.message);
                      alert(' likes count is now ' + response.likes_count);
            },
                error: function(rs, e) {
                       alert(rs.responseText);
            }
      }); 
})
</script>
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.305262 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO