title: 403 Forbidden error when making an ajax Post request in Django framework
body: <p>I am trying to integrate jquery into a web application I am making with Django framework. I am however having a hard time trying to make a simple <code>ajax</code> call to work. My template file that contains the form html and javascript to handle the ajax call looks like:</p>
  
  <pre><code>&lt;script type="text/javascript"&gt;
  $(document).ready(function() {
  $( "#target" ).submit(function() {
  console.log('Form was submitted');
  $.ajax({
          type: "POST",
          url: "/hello/",  // or just url: "/my-url/path/"
          data: {
              query: $( "#query" ).val()   
          },
          success: function(data) {
              console.log(data);
          }
      });
  return false;
    });   
    })
  &lt;/script&gt;
  &lt;form id="target" action="." method="post"&gt;{% csrf_token %}
   &lt;input id= "query" type="text" value="Hello there"&gt;
   &lt;input type="submit" value="Search Recent Tweets"&gt;
  &lt;/form&gt;
  </code></pre>
  
  <p>My <code>views.py</code> that is supposed to handle the ajax call looks like:</p>
  
  <pre><code> from django.core.context_processors import csrf
   from django.shortcuts import render_to_response
   from django.template.loader import get_template
   from django.template import Context,RequestContext
   from django.views.decorators.csrf import ensure_csrf_cookie
   from django.http import HttpResponse
  
   # access resource
   def hello(request):
    c = {}
    c.update(csrf(request))
    if request.is_ajax():
          t = get_template('template.html')
          #html = t.render(Context({'result': 'hello world'}))
          con = RequestContext(request, {'result': 'hello world'})
          return render_to_response('template.html', c, con)
    else:
          return HttpResponse('Not working!') 
  </code></pre>
  
  <p>I have tried to follow the official documentation on <a href="https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ref-contrib-csrf" rel="noreferrer">Cross-Site Request Forgery Protection</a> and also looked at several stackoverflow questions addressing a similar problem. I have included the <code>{% csrf_token %}</code> in my <code>html</code> template file but it still doesn't seem to be working. I get an error in the console suggesting that the ajax call failed:</p>
  
  <pre><code>POST http://127.0.0.1:8000/hello/ 403 (FORBIDDEN)   
  </code></pre>
  
  <p>How do I pass the <code>result</code> variable along with my http response and get the ajax call to work smoothly? Any help is deeply appreciated.</p>
  
  <p><strong>Edit-1</strong></p>
  
  <p>I wasn't supposedly passing the <code>csrf</code> token along with my post request. SO as per the documentation I added the following code to my template javascript:</p>
  
  <pre><code>function getCookie(name) {
  var cookieValue = null;
  if (document.cookie &amp;&amp; document.cookie != '') {
      var cookies = document.cookie.split(';');
      for (var i = 0; i &lt; 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;
  }
  var csrftoken = getCookie('csrftoken');
  console.log(csrftoken);
  
  //Ajax call
  function csrfSafeMethod(method) {
  // these HTTP methods do not require CSRF protection
  return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
  }
  $.ajaxSetup({
      crossDomain: false, // obviates need for sameOrigin test
      beforeSend: function(xhr, settings) {
          if (!csrfSafeMethod(settings.type)) {
              xhr.setRequestHeader("X-CSRFToken", csrftoken);
          }
      }
  });
  </code></pre>
  
  <p>When I refresh the template html page in the browser, I get <code>null</code> in the console, suggesting that the cookie is not set or not defined. What am I missing?</p>