1

I don't know python.
I'm just requesting Python REST APIs using jQuery and AJAX.

Here's my Code so far:

<!DOCTYPE html>
<html>
<head>
<title>Announcements</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div id="announcements">

</div>
<script>
$(document).ready(function(){
    $.ajax({
        dataType: "json",
        method: "GET",
        url: "/mhtsessions/annoucements/",
        data: {
          csrfmiddlewaretoken:  getCookie('csrftoken')
        },
        success: function(data){
            $("#announcements").html(data);
      }
    });
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // 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;
    }

});
</script>
</body>
</html>

I also need to pass CSRF Token to access the APIs.
Where CSRF Token is generated by Django Rest Framework.
I've seen this Question, it's not my case, and I also need to pass CSRF Token.

EDIT:
Also, I'm getting response in JSON in POSTMAN, I just need JS or AJAX Code to show it to users.

Nirav Madariya
  • 1,470
  • 2
  • 24
  • 37

1 Answers1

1

Actually, you dont need to use csrf_token for GET request (requests that are not meant to change data in database). I will write a working example for POST request using jquery.

   $('.deleteCheckpoint').click(function(e){
      e.preventDefault();
      $.ajax({
        type: "POST",
        url: 'checkpoint/delete/',
        data: {
          csrfmiddlewaretoken:  getCookie('csrftoken')
        },
      success: function(){
        notification_message('Checkpoint was succesfully deleted');
      }
      });
   });

The function getCookie is from the official documentation https://docs.djangoproject.com/en/1.11/ref/csrf/

Make sure that you have already store the cookie with the csrf_token, if you havent then include a {% csrf_token %} in you html page. Django will automatically store the csrf_token in the browser, as a result the getCookie function will return the correct value.