Skip to content

Instantly share code, notes, and snippets.

@goldhand
Created October 8, 2013 20:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save goldhand/3a4e2fef46a0ec1d9e5d to your computer and use it in GitHub Desktop.
Save goldhand/3a4e2fef46a0ec1d9e5d to your computer and use it in GitHub Desktop.
attach a csrf token to ajax posts
/**
* by: goldhand
* Date: 10/8/13
* Time: 1:29 PM
*/
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;
}
$(document).ready(function() {
$("#button").click(function(){
$.ajax({
type : "POST",
url : "{% url 'getlist' %}",
data : {
msg : 'abcd',
csrfmiddlewaretoken: getCookie('csrftoken')
}
}).done(function(data){
alert(data.message);
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment