I have the following ajax function which is giving me a cross site forgery request token error once I get past the minimumlengthinput of 3 with the select2 control. Knowing this I attempted to add { csrfmiddlewaretoken: '{{ csrf_token }}' }, to my data:. After adding the csrfmiddlewaretoken I'm still getting the CSRF token missing or incorrect error. I believe it has something to do with the my function for the searchFilter and searchPage follows. What is the proper way to do this?
// using jQuery
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;
}
var csrftoken = getCookie('csrftoken');
$(document).ready(function () {
$('.selectuserlist').select2({
minimumInputLength: 3,
allowClear: true,
placeholder: {
id: -1,
text: 'Enter the 3-4 user id.',
},
ajax: {
type: 'POST',
url: '',
contentType: 'application/json; charset=utf-8',
async: false,
dataType: 'json',
data: { csrfmiddlewaretoken: csrftoken },
function(params) {
return "{'searchFilter':'" + (params.term || '') + "','searchPage':'" + (params.page || 1) + "'}";
},
processResults: function (res, params) {
var jsonData = JSON.parse(res.d);
params.page = params.page || 1;
var data = { more: (jsonData[0] != undefined ? jsonData[0].MoreStatus : false), results: [] }, i;
for (i = 0; i < jsonData.length; i++) {
data.results.push({ id: jsonData[i].ID, text: jsonData[i].Value });
}
return {
results: data.results,
pagination: { more: data.more,
},
};
},
},
});
});
My view has the POST method and csrf_token as well.
{% block content %}
<form action = "{% url 'multiresult' %}" form method = "POST">
{% csrf_token %}
{% block extra_js %}
{{ block.super }}
{{ form.media }}
The response from the console is
Forbidden (CSRF token missing or incorrect.): /search/multisearch/ [29/Mar/2018 09:14:52] "POST /search/multisearch/ HTTP/1.1" 403 2502