0

I'm trying implement a like button that changes color when clicked. I am trying to replace the image dynamically using jQuery.

<div class = "col-sm-10" style = "margin-top: 2%">
  <input style = "width : 4%; height: 4%" type = "image" id = {{schedule.id}} + "image" class = "likes"
  data-scheduleid = "{{schedule.id}}" data-user = "{{curruser.person.id}}"
  src = "{% static 'img/notliked2.png' %}"/>
</div>

This is image file that gets pressed as a button. Essentially, I am trying to change the image file on click.

$(document).ready(function() {
  $('.likes').click(function(e){
    var sched_id;
    var curruser;
    sched_id = $(this).attr("data-scheduleid");
    curruser_id = $(this).attr("data-user");
    $.get('/profiles/like_schedule/', {schedule_id: sched_id, current_user: curruser_id}, function(data){
      var first = data.split("/")
      $('#' + sched_id).html(first[0]);
      console.log(first[1])
      //$('#likes').html("<input style = 'width : 4%; height: 4%' type = 'image' id = {{schedule.id}} class = 'likes' data-scheduleid = '{{schedule.id}}' data-user = '{{curruser.person.id}}' src = {% static 'img/" + first[1] + "' %}/>");
      $('.' + sched_id + "image").attr("src", "{% static 'img/" + first[1] + "' %}")
      e.preventDefault();
    });
  });
});

This is the jQuery. I logged first[1], and it is correct. It alternates between "notliked2.png" and "liked2.png" when someone likes and unlikes. But for some reason replacing the image source doesn't work. I even tried replacing the entire html, and it still doesn't work. Does someone know what is going on?

Thank you,

Albert Jin

edit: Here is the views code.

def like_schedule(request):
    sched_id = None
    if request.method == 'GET':
        sched_id = request.GET['schedule_id']
        curruser_id = request.GET['current_user']
    likes = 0
    liked = "liked2.png"
    if sched_id:
        sched = schedules.objects.get(id = int(sched_id))
        curruser = person.objects.get(id = int(curruser_id))
        if curruser in sched.person_likes.all():
            liked = "notliked2.png"
            sched.likes -= 1
            sched.person_likes.remove(curruser)
        else:
            sched.likes += 1
            sched.person_likes.add(curruser)
        likes = sched.likes
        sched.save()
    return HttpResponse(str(likes) + "/" + str(liked))

As for the repeat posts, I did try those but they do not work.

Albert Jin
  • 53
  • 7
  • 2
    Possible duplicate of [Refresh image with a new one at the same url](https://stackoverflow.com/questions/1077041/refresh-image-with-a-new-one-at-the-same-url) – Luke Oct 16 '17 at 06:41
  • possible duplicate of https://stackoverflow.com/questions/36525744/replacing-images-in-django-with-jquery – Dhaval Pankhaniya Oct 16 '17 at 06:55

2 Answers2

0

You are using django sytax in your javascript code. You cant use the static function like this:

$('.' + sched_id + "image").attr("src", "{% static 'img/" + first[1] + "' %}")

I would replace the current url and only replace the dynamic part of the url, like so:

var src = $('.' + sched_id + "image").attr("src");
$('.' + sched_id + "image").attr("src", src.slice(0, src.indexOf('img/')) + 'img/" + first[1]);
Nachshon Schwartz
  • 15,289
  • 20
  • 59
  • 98
  • hmm, thanks for the reply! Unfortunately, this does not work either. Should i use replace() or something? I also tried replacing it with just a url from the web to some picture, and it still did not work. Does anyone know what is going on? – Albert Jin Oct 16 '17 at 06:48
  • @AlbertJin after making this change, do you see the `src` attribute updated if you inspect the element? – Mohit Bhardwaj Oct 16 '17 at 06:50
  • hmm, no i get this error "Cannot read property 'slice' of undefined. " – Albert Jin Oct 16 '17 at 06:53
  • corrected it slice function needed `.slice(0, index)` instead of `.slice(index)` – Nachshon Schwartz Oct 16 '17 at 06:53
  • Also, check out my edit from above! I tried using a web url and it did not work either :( – Albert Jin Oct 16 '17 at 06:53
  • like this? "$('.' + sched_id + "image").attr("src", src.slice(0, src.indexOf('img/')) + "img/" + first[1]);" It still gives me the same error :( – Albert Jin Oct 16 '17 at 06:54
0

Not sure of how is the format of the $.get response (you don't show it in the question), but looking at your code this should be enough...

$(document).ready(function() {

    $('.likes').click(function(e) {

        e.preventDefault();

        var $img = $(this);

        $.get('/profiles/like_schedule/',{ schedule_id: $img.data("scheduleid"), current_user: $img.data("user") }, function(data) {
            $img.attr('src','img/' + data.split("/")[1])
        });
    });
});

One posible problem is that you're having a caching problem, so your get call is not being executed. If that's your case, you can force your server to execute that call just adding some extra inconstant parameter...

$.get('/profiles/like_schedule/',{ dummy: (new Date()).getTime(), schedule_id: $img.data("scheduleid"), current_user: $img.data("user") }, function(data) {
    $img.attr('src','img/' + data.split("/")[1])
});

NOTE: When you want to get the value of a data-whatever attribute in jquery, you have the .data('whatever') function (is designed for that).

A. Iglesias
  • 2,625
  • 2
  • 8
  • 23
  • Have you tried my code? Do you get any console error? – A. Iglesias Oct 16 '17 at 08:37
  • You're probably having caching issues. I've edited the answer. Check that out. – A. Iglesias Oct 16 '17 at 08:42
  • I get this error Uncaught ReferenceError: $img is not defined. What is $img for exactly? – Albert Jin Oct 16 '17 at 17:27
  • And are you sure you have the line `var $img = $(this);` before the get? `$img` is a variable to save the jquery object of the image you have clicked (you save `$(this)`), so you can use it to access its properties, attributes, etc. – A. Iglesias Oct 16 '17 at 18:05
  • Oh i see. Hmm I seem to be getting "http://127.0.0.1:8000/profiles/like_schedule/?dummy=1508195550853 500 (Internal Server Error)". When i run it without the dummy, i get the same error, but the url just ends at like_schedule/ – Albert Jin Oct 16 '17 at 23:13
  • That means your web server is not answering correctly. The url is the same you have in your question (forget the dummy for now), so you have to check that to find out why is not answering you. Maybe you have changed something doing all the tests. – A. Iglesias Oct 17 '17 at 04:38