title: Dealing with concurrent Ajax requests
body: <p>I'm trying to do the following:</p>
  
  <ul>
  <li>I have a list of links, each performing a different Ajax call when clicked.</li>
  <li>Each Ajax response is assigned a target where it will be displayed.</li>
  <li>While a request is being processed, the links can still be clicked (= further Ajax calls).</li>
  <li>The example below has two targets and four links: two point to DIV#d1, two point to DIV#d2.</li>
  </ul>
  
  <p>How can I make sure that only the response to the last request sent will eventually be displayed in its target DIV ?</p>
  
  <p>If I click on the link labelled <code>Data1</code>, then <code>Data2</code>, the first call must be aborted because Response1 could arrive after Response2. The problem seems to imply that I must keep track of previous requests for each target, so I can abort them whenever a new request is made.</p>
  
  <p>I've written this piece of code. I'd like to know if you think this is the approach is right.</p>
  
  <pre><code>&lt;!DOCTYPE html&gt;
  &lt;html&gt;
    &lt;head&gt;
      &lt;meta charset="UTF-8" /&gt;
      &lt;title&gt;&lt;/title&gt;
    &lt;/head&gt;
    &lt;body&gt;
      &lt;ul&gt;
        &lt;li&gt;&lt;a href="data1.htm" class="trigger" data-target="d1"&gt;Data 1&lt;/a&gt;&lt;/li&gt;
        &lt;li&gt;&lt;a href="data2.htm" class="trigger" data-target="d1"&gt;Data 2&lt;/a&gt;&lt;/li&gt;
        &lt;li&gt;&lt;a href="data3.htm" class="trigger" data-target="d2"&gt;Data 3&lt;/a&gt;&lt;/li&gt;
        &lt;li&gt;&lt;a href="data4.htm" class="trigger" data-target="d2"&gt;Data 4&lt;/a&gt;&lt;/li&gt;
      &lt;/ul&gt;
      &lt;div id="d1"&gt;&lt;/div&gt;
      &lt;div id="d2"&gt;&lt;/div&gt;
      &lt;script type="text/javascript" src="/test/jquery-1.7.1.min.js"&gt;&lt;/script&gt;
      &lt;script type="text/javascript"&gt;
        $(function(){
          var register = {};
  
          $(".trigger").on("click", function() {
            var target = $(this).attr("data-target");
            var url = $(this).attr("href");
            if (register[target] == undefined) register[target] = [];
  
            ajaxCall = $.get(url, function(data) { // Ajax request
              $("#" + target).html(data);
            });
  
            for (a in register[target]) { // Aborts existing ajax requests for this target
              register[target][a].abort();
            }
            register[target] = []; // Empty register for this target
            register[target].push(ajaxCall); // Register current ajax request
  
            return false;
          });
  
        });
      &lt;/script&gt;
    &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>