How to make auto logout using ajax and django

I would like to write js function for auto logout using ajax and django. Actually i did and succeded. it works fine. but i do not know is it a proper way to do it. i post my code and i need your reviews and revised or improved code or proper way to implement the auto logout funtion.

Here my code. views.py


def user_logout(request):
    logout(request)
    is_ajax = request.headers.get("X-Requested-With") == "XMLHttpRequest"
    if is_ajax:        
        print("auto logout works")
        return JsonResponse({"redirect_link":"/login"},status=200)
    else:
        print("manuel logout works")        
        return redirect("/login")

ajax


<script language="javascript">
  jQuery(document).ready(function(){
    function getCookie(name) {
  let cookieValue = null;
  if (document.cookie && document.cookie !== "") {
    const cookies = document.cookie.split(";");
    for (let i = 0; i < cookies.length; i++) {
      const cookie = cookies[i].trim();
      // Does this cookie string begin with the name we want?
      if (cookie.substring(0, name.length + 1) === (name + "=")) {
        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
        break;
      }
    }
  }
  return cookieValue;
}
             setInterval(function(){
                 jQuery.ajax({
                     url: "{% url 'user-logout' %}",
                     headers: {"X-Requested-With": "XMLHttpRequest","X-CSRFToken": getCookie("csrftoken"),},
                     type: 'GET',
                     dataType: 'json',
                     success:function(response){
                         window.location.href="{% url 'user-login' %}"
                         alert("You are logged out");
                     }
                 });      
             }, 5000);
         });
</script>
Back to Top