2

I want to replace my jquery ajax code with es6 fetch api under django framework this is my jquery ajax code

var csrf = $('meta[name="csrf_token"]').attr('value')
        //comment vote
        $("#comment_box").on('click', "a.vote-up", function() {
            var voteID = parseInt(this.id.split("-")[1]);
            $.ajax({
                url : "/vote_json/",
                type : "POST",
                dataType: "json",
                data : {
                    "comment_id": voteID,
                    "vote": $('#up-' + voteID).attr('value'),
                    csrfmiddlewaretoken: csrf
                },
                success : function(json) {
                    $('#up-' + voteID).html('<i class="chevron vote up icon"></i>' + json.vote);
                    $('#up-' + voteID).popup({
                        position    : 'top center',
                        content     : json.msg,
                        on          : 'manual'
                    });
                    $('#up-' + voteID).popup('show');
                    setTimeout(function (){$('#up-' + voteID).popup('hide');}, 3000);
                },
                error : function(xhr,errmsg,err) {
                    alert(xhr.status + ": " + xhr.responseText);
                }
            });
            return false;
        });

and this code is es6 fetch api

let csrf = document.querySelector('meta[name="csrf_token"]').getAttribute('value');
    //comment vote
    [].forEach.call(document.querySelectorAll('a.vote-up'), function (voteup) {
        voteup.addEventListener('click', function () {
            let voteid = parseInt(voteid.id.split("-")[1]);
            fetch('/vote_json/', {
                method: 'POST',
                body: JSON.stringify({
                    comment_id: voteid,
                    vote: document.querySelector('#up-' + voteid).getAttribute('value'),
                    csrfmiddlewaretoken: csrf
                })
            }).then(function (response) {
                return response.json();
            }).then(function (json) {
                document.querySelector('#up-' + voteid).innerHTML = '<i class="chevron vote up icon"></i>' + json.vote
                document.querySelector('#up-' + voteid.popup({
                    position    : 'top center',
                    content     : json.msg,
                    on          : 'manual'
                }),
                document.querySelector('#up-' + voteid).popup('show'),
                setTimeout(function () {
                    document.querySelector('#up-' + voteid).popup('hide'), 3000
                })
                )
            })
        })
    }

and this code is my view in django

def vote(request):
    comment_pk    = request.POST.get('comment_id')
    vote          = request.POST.get('vote')
    comment       = Comment.objects.get(pk=comment_pk)
    if vote == 'true':
        comment.up += 1
        comment.save()
        response_dict = dict(vote=comment.up)
    elif vote == 'false':
        comment.down -= 1
        comment.save()
        response_dict = dict(vote=comment.down)
    return HttpResponse(json.dumps(response_dict), content_type='application/javascript')

the problem is that in jquery code everything is working but in es6 django responsed "CSRF verification failed. Request aborted." and I tested fetch ajax code in Get method without body block and another django view in this mode works fine

1 Answers1

1

Copy pasted from here.

The solution was in the getCookie() method.

fetch("/graphql", {
        method: "POST",
        credentials: "same-origin",
        headers: {
          "X-CSRFToken": getCookie("csrftoken"),
          "Accept": "application/json",
          'Content-Type': 'application/json'
        },
        body:JSON.stringify(query)
      })

And of course the method has to be on the same page. Taken from Django Docs.

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;
}
Community
  • 1
  • 1
Ska
  • 6,658
  • 14
  • 53
  • 74