title: Jquery Ajax beforeSend and success,error & complete
body: <p>I have a problem with multiple ajax functions where the <code>beforeSend</code> of the <em>second</em> ajax post is executed before the <code>complete</code> function of the <em>first</em> ajax.</p>
  
  <p>The loading class I am adding to the placeholder before sending is working for the first ajax call. However soon after the first ajax request completes the class is removed and never appends again on the second and further calls (remember recursive calls).</p>
  
  <p>While debugging it shows that the <code>beforeSend</code> function of the second ajax call is called first and the <code>complete</code> function of the first ajax call is called later. Which is obvious, because the return data inserted in the page from the first ajax call starts the second call.</p>
  
  <p>In short it's mixed up. Is there any way this can be sorted out?</p>
  
  <p>The function code is as follows</p>
  
  <pre><code>function AjaxSendForm(url, placeholder, form, append) {
  var data = $(form).serialize();
  append = (append === undefined ? false : true); // whatever, it will evaluate to true or false only
  $.ajax({
      type: 'POST',
      url: url,
      data: data,
      beforeSend: function() {
          // setting a timeout
          $(placeholder).addClass('loading');
      },
      success: function(data) {
          if (append) {
              $(placeholder).append(data);
          } else {
              $(placeholder).html(data);
          }
      },
      error: function(xhr) { // if error occured
          alert("Error occured.please try again");
          $(placeholder).append(xhr.statusText + xhr.responseText);
          $(placeholder).removeClass('loading');
      },
      complete: function() {
          $(placeholder).removeClass('loading');
      },
      dataType: 'html'
  });
  }
  </code></pre>
  
  <p>And the data contains the following snippet of javascript/jquery which checks and starts another ajax request.</p>
  
  <pre><code>&lt;script type="text/javascript"&gt;//&lt;!--
   $(document).ready(function() {
      $('#restart').val(-1)
      $('#ajaxSubmit').click();
  });
  //--&gt;&lt;/script&gt;
  </code></pre>