Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

jquery.postcsrf.js 1.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /**
  2. * Wrapper for jQuery's $.post() that retrieves the CSRF token from the browser
  3. * cookie and sets then sets "X-CSRFToken" header in one fell swoop.
  4. *
  5. * Based on the example code given at the Django docs:
  6. * https://docs.djangoproject.com/en/1.9/ref/csrf/#ajax
  7. *
  8. * Use as you would $.post().
  9. */
  10. (function($) {
  11. $.postCSRF = function(url, data, callback, type) {
  12. function csrfSafeMethod(method) {
  13. // these HTTP methods do not require CSRF protection
  14. return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
  15. }
  16. function getCookie(name) {
  17. var cookieValue = null;
  18. if (document.cookie && document.cookie !== '') {
  19. var cookies = document.cookie.split(';');
  20. for (var i = 0; i < cookies.length; i++) {
  21. var cookie = jQuery.trim(cookies[i]);
  22. // Does this cookie string begin with the name we want?
  23. if (cookie.substring(0, name.length + 1) == (name + '=')) {
  24. cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
  25. break;
  26. }
  27. }
  28. }
  29. return cookieValue;
  30. }
  31. var csrftoken = getCookie('csrftoken');
  32. // shift arguments if data argument was omitted
  33. if ($.isFunction(data)) {
  34. type = type || callback;
  35. callback = data;
  36. data = undefined;
  37. }
  38. return $.ajax(jQuery.extend({
  39. url: url,
  40. type: "POST",
  41. dataType: type,
  42. data: data,
  43. success: callback,
  44. beforeSend: function(xhr, settings) {
  45. if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
  46. xhr.setRequestHeader("X-CSRFToken", csrftoken);
  47. }
  48. }
  49. }, jQuery.isPlainObject(url) && url));
  50. };
  51. }(jQuery));