0

I'm trying to send a value to the URL, whenever event occurs it shows:

error that the Forbidden (CSRF token missing or incorrect.): /mapreq [03/Nov/2017 11:08:27] "POST /mapreq HTTP/1.1" 403 2502

This is the script:

<script>
        $(document).ready(function () {
            $('path').mouseup(function () {
                document.getElementById('state').innerHTML = $(this).attr('aria-label');
                var state_lbl = document.getElementById('state').innerHTML = $(this).attr('aria-label');
                loadstate(state_lbl);

            })
        });

        function loadstate(state_lal) {
            $.ajax({
                type: "POST",
                url: "mapreq",
                data: {'state': state_lal}
            });
        }
    </script>
Xplora
  • 837
  • 3
  • 12
  • 24
SACHIN CHAVAN
  • 415
  • 5
  • 16
  • 1
    Possible duplicate of [Django CSRF check failing with an Ajax POST request](https://stackoverflow.com/questions/5100539/django-csrf-check-failing-with-an-ajax-post-request) – Selcuk Nov 03 '17 at 06:21

2 Answers2

1

You need to pass the csrf token. It is important to protect your users data.

With a JavaScriptCookie you can get it like that:

var csrftoken = Cookies.get('csrftoken');
var data = new FormData();

data.append('state',state_lal);
data.append('csrftoken', csrftoken);


 function loadstate(state_lal) {
        $.ajax({
            type: "POST",
            url: "mapreq",
            data: data,
        });

If you do not want to use a third-party just have a look at this documentation. Here is also the third-party mentioned but also the way without it.

Coder949
  • 987
  • 1
  • 8
  • 29
0

In your settings.py file comment or remove the 'django.middleware.csrf.CsrfViewMiddleware' line from middelware classes.

`MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'django.middleware.common.CommonMiddleware',
#     'django.middleware.csrf.CsrfViewMiddleware',
)`

Then you will not get the error message related to CSRF token.

Otherwise Add CSRF key in parameter list like:

'data: { CSRF: getCSRFTokenValue()}'
sachin
  • 379
  • 3
  • 16
  • Really ? You should not do that ! csrf-token are very important to protect your users data. – Coder949 Nov 03 '17 at 06:57
  • The above thing is for simple use case . But yes it is important to keep csrf token for safety . For that you need to include csrf key in the parameter data: { CSRF: getCSRFTokenValue()} – sachin Nov 03 '17 at 11:39