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.