Skip to content

Instantly share code, notes, and snippets.

@Nicksil
Created November 2, 2013 04:05
Show Gist options
  • Save Nicksil/7275358 to your computer and use it in GitHub Desktop.
Save Nicksil/7275358 to your computer and use it in GitHub Desktop.
Django CSRF_TOKEN AJAX Fix
$(document).ready(function() {
// AJAX GET
$('.get-more').click(function() {
$.ajax({
type: "GET",
url: "/ajax/more/",
success: function(data) {
for(i=0; i<data.length; i++) {
$('ul').append('<li>'+data[i]+'</li>');
}
}
})
});
// AJAX POST
$('.add-todo').click(function() {
$.ajax({
type: 'POST',
url: '/ajax/add/',
dataType: 'json',
data: {'item': $('.todo-item').val()},
success: function(data) {
alert(data.message);
}
});
});
// CSRF
function getCookie(name) {
var cookieValue = null;
var i = 0;
if(document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for(i; i<cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
if(cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
function csrfSafeMethod(method) {
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
crossDomain: false,
beforeSend: function(xhr, settings) {
if(!csrfSafeMethod(settings.type)) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment