title: Server request completing before AJAX beforeunload call
body: <p>I have a Rails 4 chat app that is having a small timing issue. When the user is on the active chatting page and they want to leave, they should be notified by the app that they have current chats and they must verify that they wish to leave the page. I have this working using the following jQuery:</p>
  
  <pre><code>jQuery(window).on('beforeunload', function(){
    if(jQuery('#chatListUL li').length &gt; 0){
      return 'You have active sessions. Are you sure you want to leave this page?';
    }
  }).unload(function(){
    jQuery.ajax({
      url: '/chat/chat_sessions/removeUserFromAll',
      type: 'DELETE',
      dataType: 'json',
      async: false
    });
  });
  </code></pre>
  
  <p>This is working as expected and will remove the user from all of their current chats. </p>
  
  <pre><code>...
  enrolled_chats = ChatSessionUserList.where(user_id: current_user.id)
  enrolled_chats.each do |ec|
    chat_session = ec.chat_session
    ec.destroy
    if chat_session.users.length &lt; 2
      chat_session.open = false
      chat_session.save
    ...
    end
  end
  </code></pre>
  
  <p>However if the link to go back to the overview chat page that lists all current and pending chats is used to navigate away from the page, then the following is run in the controller on the server:</p>
  
  <pre><code>...
  @current_filled_requests = ChatSession.where(open: true)
  ...
  </code></pre>
  
  <p>The problem is when the overview page loads, it counts all of the previous active chats as still open. Looking in the log, I can see the request to the server for the overview page completing before the AJAX request that was sent in the beforeunload action. So those chats that user just left are being put into the instance variable before being marked as closed.</p>
  
  <p>How can I make sure the beforeunload call completes before the actual server request? I know I could put an AJAX call on the overview page that would load the active chats after the page had loaded; but I was hoping to avoid another call to the server.</p>