I developed my application on Linux and the AJAX requests work fine. I have pulled the application to a Windows machine but the AJAX requests fail, I just get a 403 Forbidden error. From looking online, I think it is a problem with the csrf token. In Linux, I can see csrftoken:"AjQzJy3tRZ2awslgdibkDTvQgANFQKmP"
under Cookies of the AJAX requests. I don't see any cookies set in Windows.
This is the Javascript code I use to get the csrf cookie. It is from https://docs.djangoproject.com/en/1.8/ref/csrf/
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;
}
This is where I submit the AJAX request:
function refreshInformation(){
$.ajax({
type: "POST",
url: "get_flows_info",
data: {
csrfmiddlewaretoken: getCookie('csrftoken')
}
dataType : "json",
async : true,
error : function(data){
alert('AJAX error:' + data);
},
success : function(json_data){
// do stuff...
},
});
}
This is the view being requested:
def get_flows_info(request):
if request.is_ajax():
# do stuff...
return HttpResponse(json.dumps(ret), content_type='application/json')
I found this: Django CSRF check failing with an Ajax POST request but the jQuery doesn't make any difference.
Any help?
Thanks.