title: Before firing AJAX event, manipulate DOM -- CSRF Error
body: <p>I'm working with Django, trying to make a chained AJAX call -- that is, a call that, when returned, kicks off more AJAX calls. I've been over the various methods of dealing with CSRF tokens and AJAX that the Django documentation provides, to no avail.</p>
  
  <p>I have working code that allows for this chained AJAX call to successfully go through:</p>
  
  <pre><code>frm.submit(function(e){
      $.ajax({
          type: frm.attr('method'),
          url: frm.attr('action'),
          data: frm.serialize(),
          headers: {'X-CSRFToken':csrftoken},
          success: function(data, status){
              $('#queue_div').append("&lt;div class='container'&gt;"+data['group_name']+"- "+data['client']+"&lt;div id='queue"+counter+"'&gt;&lt;/div&gt;&lt;/div&gt;");
  
              var div_id = 'queue'+counter;
              data['div_id'] = div_id;
  
              var token = $.cookie('csrftoken');
              data['csrf'] = token;
  
              $('#'+div_id).html(data['status']);
  
              callbackAJAX(data);
              } //end success function
      }); //end ajax function
      e.preventDefault();
  </code></pre>
  
  <p>But when you delay the form event from firing the AJAX event right away, either by using "beforeSend" (as below):</p>
  
  <pre><code>        var data = {'group_name':'name', 'client':'MrClient'}
          var counter = 0
          frm.submit(function(e){
          $.ajax({
              type: frm.attr('method'),
              url: frm.attr('action'),
              data: frm.serialize(),
              headers: {'X-CSRFToken':csrftoken}
              beforeSend:function(e){
                 $('#foo').append('&lt;div class='container'&gt;"+data['group_name']+"- "+data['client']+"&lt;div id='queue"+counter+"'&gt;&lt;/div&gt;&lt;/div&gt;');
               } .....
  </code></pre>
  
  <p>or by adding an event right before the $.ajax call (as below):</p>
  
  <pre><code>        frm.submit(function(e){
             $('#foo').append('&lt;div class='container'&gt;"+data['group_name']+"- "+data['client']+"&lt;div id='queue"+counter+"'&gt;&lt;/div&gt;&lt;/div&gt;');          
             $.ajax({
              type: frm.attr('method')....
  </code></pre>
  
  <p>You get a CSRF error.</p>
  
  <p>I was successful in doing very, very simple functions such as the following:</p>
  
  <pre><code>        var counter = 0;
          frm.submit(function(e){         
             $.ajax({
              type: frm.attr('method'),
              sendBefore: function(e){
                counter++;
          }
  </code></pre>
  
  <p>But that's it. Anything more complicated gets rejected. I'm thoroughly confused as how to make heads or tails of what is actually happening OR what is acceptable to Django. &amp; its CSRF protection.</p>