skip to Main Content

I’ve been testing my site by having friends try it, and some friends get the 403 Forbidden error on any function using ajax. I’m confused why only some of them get the error, especially when everyone used the same browser. Does anyone know why? I’m using Django as a framework and I think I’ve done everything in the documentation here

Example of one of my functions using ajax:

$('#button').click(function(){
        $.ajax({
            url: '/get_url/',
            type: "POST",
            data: {
                data_name: data_to_send
            },
            beforeSend: function (xhr) {
                xhr.setRequestHeader("X-CSRFToken", csrftoken);
            },
            success: function (data) {
                //change some html text using data
            },
            error: function (error) {
                console.log(error);
            }
        });
    });

2

Answers


  1. Chosen as BEST ANSWER

    Fixed by making sure all of my form tags had method='post' and {{ crsf_token }}.


  2. use this:

    $('#button').click(function(){
        $.ajax({
            url: '/get_url/',
            type: "POST",
            data: {
                data_name: data_to_send
            },
            headers: {
                "X-CSRFToken": "{{ csrf_token }}",
            },
            success: function (data) {
                //change some html text using data
            },
            error: function (error) {
                console.log(error);
            }
        });
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search