title: successful and fail callbacks in ajax
body: <p>I have this functions which sends a <code>get</code> request to a server. It can be called with optional params so with/out data, successful or fail callback. I call it like this:</p>
  
  <pre><code>get('ajax/search.php', {q: q}, function(data) {
      //success
  }, function() {
      //fail
  });
  </code></pre>
  
  <p><br></p>
  
  <p>The problem is that <code>both callback function are being called</code>. I want to call only one of them. So if the request is successful <code>done()</code> will be called, or if failed <code>fail()</code> will be called</p>
  
  <p>I know you can do this in jQuery but I decided to switch to pure JavaScript for speed and performance.</p>
  
  <pre><code>function get() {
      var data,
          done,
          fail,
          done_index = null,
          str = '',
          ajax = new XMLHttpRequest(),
          url = arguments[0];
  
      for(var i=0; i&lt;arguments.length; i++) {
          if(typeof arguments[i] == 'object') {
              data = arguments[i];
  
              for(var key in data) {
                  if(str != "") str += "&amp;";
  
                  str += key + "=" + encodeURIComponent(data[key]);
              }
  
              if(str != '') url += '?';
          } else if(typeof arguments[i] == 'function') {
              if(done_index == null) {
                  done = arguments[i];
                  done_index = i;
              }
  
              if(i != done_index) {
                  fail = arguments[i];
              }
          }
      }
  
      ajax.onreadystatechange = function() {
          if(ajax.readyState === XMLHttpRequest.DONE &amp;&amp; ajax.status === 200) {
              if(done) {
                  if(JSON.parse(ajax.responseText))
                      done(JSON.parse(ajax.responseText));
                  else if(ajax.responseText == '')
                      done();
              }
  
              if(fail) fail();
          }
      };
  
      ajax.open('get', url + str);
      ajax.send();
  }
  </code></pre>