'Django: ajax not returning or sending any data in django

i am creating a simple like button with ajax, i have followed the tutorial but it seems, that i am missing something, i am not getting any error either in the console in my django terminal but when i click the button no data get sent, evrything just remains the same way, and this is not what i am expecting, i know i am missing something somewhere and i cannot really tell where this error is coming from.

views.py

@login_required
def like(request):
    if request.POST.get("action") == 'post':
        result = ""
        id = int(request.POST.get('courseid'))
        course = get_object_or_404(Course, id=id)

        if course.like.filter(id=request.user.id).exists():
            course.like.remove(request.user)
            course.like_count -= 1
            result = course.like_count
            course.save()
        else:
            course.like.add(request.user)
            course.like_count += 1
            result = course.like_count
            course.save()
        return JsonResponse({'result': result})

urls.py NOTE:I don't know if i need a slug in this url path

    path('like/', views.like, name="like"),

base.html

   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

course-detail.html

<li><button id="like-button" value="{{course.id}}">like</button><span id="like-count">{{course.llke_count}}</span></li>



<script type="text/javascript">
        
    $(document).on("click", '#like-button', function(e){
        e.preventDefault()
        $.ajax({
            type: 'POST',
            url: '{% url 'course:like' course.slug %}',
            data: {
                courseid: $('#like-button').val(),
                csrfmiddlewaretoken: $("input[name=csrfmiddlewaretoken]").val(),
                action: 'post'
            },
            success: function(json){
                document.getElementById("like-count").innerHTML = json['result']
                console.log(json)
            },
            error: function (xhr, errmsg, err)
            console.log(xhr)
            console.log(errmsg)
            console.log(err)
        })
    })

</script>

this is all the code i have written for the functionality, if there is any other thing to be provided i will update the question

UPDATE AFTER FIRST ANSWER #####################################################################

Now when i click the like button is does show an visible error but the like count now shows undefined and in my chrome dev tools is shows failed to load response data because this request was redirected

enter image description here



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source