title: Browser sometimes displays JSON text instead of desired page
body: <p>I have been experiencing an intermittent issue in my Rails app, and I'm having trouble figuring out what is going on.  When the user logs in, they see a dashboard that contains some JavaScript code which performs an AJAX call to an action.  Occasionally, instead of seeing the dashboard, when the user logs in, they see the JSON response text from the action instead of the dashboard (in Chrome) or they download a .json file (Firefox).  It's intermittent and doesn't usually happen, but it's really annoying when it does occur.</p>
  
  <p>Here's a dumbed down version of some of the code:</p>
  
  <p>JS running in the template head:</p>
  
  <pre><code>$(function () {
      var remoteLink = $('#remoteLink');
      remoteLink.live("ajax:complete", function () {
          setTimeout(function () {
             loadCount();
          }, 30000);
      });    
  
      loadCount();
  
      function loadCount() {
        remoteLink.click();
      }
  });
  </code></pre>
  
  <p>And the link in the template:</p>
  
  <pre><code>&lt;%= link_to 'get count (hidden)', {:controller =&gt; 'something', :action =&gt; 'count'}, 
              :id =&gt; 'remoteLink', :class =&gt; 'hidden', :remote =&gt; true, 'data-type' =&gt; 'json' %&gt;
  </code></pre>
  
  <p>And the controller action:</p>
  
  <pre><code>def count
      render :json =&gt; get_counts_function_returning_a_hash
  end
  </code></pre>
  
  <p>My hunch is that it's a race condition -- perhaps related to the use of setTimeout? -- but I haven't been able to verify that hunch.  Can anyone tell me what might be going on here?  I've seen this in the wild on other sites, too -- also intermittent, not generally occurring but annoying when it happens.</p>