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.

hitcount-jquery.js 1.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. $(document).ready(function() {
  2. /**
  3. * https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax
  4. *
  5. * Remember you will need to ensure csrf tokens by adding:
  6. * @ensure_csrf_cookie to your views that require this javascript
  7. *
  8. * Also, you will probably want to include this with your other sitewide
  9. * javascript files ... this is just an example.
  10. */
  11. if ( typeof hitcountJS === 'undefined' ) {
  12. // since this is loaded on every page only do something
  13. // if a hit is going to be counted
  14. return;
  15. }
  16. var hitcountPK = hitcountJS['hitcountPK'];
  17. var hitcountURL = hitcountJS['hitcountURL'];
  18. var csrftoken = getCookie('csrftoken');
  19. $.ajaxSetup({
  20. beforeSend: function(xhr, settings) {
  21. if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
  22. xhr.setRequestHeader("X-CSRFToken", csrftoken);
  23. }
  24. }
  25. });
  26. $.post( hitcountURL, { "hitcountPK" : hitcountPK },
  27. function(data, status) {
  28. console.log(data); // just so you can see the response
  29. if (data.status == 'error') {
  30. // do something for error?
  31. }
  32. }, 'json');
  33. });
  34. function getCookie(name) {
  35. var cookieValue = null;
  36. if (document.cookie && document.cookie != '') {
  37. var cookies = document.cookie.split(';');
  38. for (var i = 0; i < cookies.length; i++) {
  39. var cookie = jQuery.trim(cookies[i]);
  40. // Does this cookie string begin with the name we want?
  41. if (cookie.substring(0, name.length + 1) == (name + '=')) {
  42. cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
  43. break;
  44. }
  45. }
  46. }
  47. return cookieValue;
  48. }
  49. function csrfSafeMethod(method) {
  50. // these HTTP methods do not require CSRF protection
  51. return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
  52. }