title: Is it possible to refresh partial frequently using Ajax?
body: <p>In background, I want it to reload and shows the number how many unread messages are there.<br>
  I want that without refreshing page.  I mean using ajax.  </p>
  
  <p>If I had this in menu, how can I refresh only this section every 30 secs?</p>
  
  <pre><code>&lt;li&gt;&lt;%= link_to sanitize('&lt;i class="icon-envelope"&gt;&lt;/i&gt; ') + "received messages" + sanitize(' &lt;span class="badge badge-info"&gt;'+current_user.mailbox.inbox(:read =&gt; false).count(:id, :distinct =&gt; true).to_s+'&lt;/span&gt;'), messages_received_path  %&gt;&lt;/li&gt;
  </code></pre>
  
  <p>messages_controller.rb</p>
  
  <pre><code>  def received
      if params[:search]
       @messages = current_user.mailbox.inbox.search_messages(@search).page(params[:page]).per(10)
      else
       @messages = current_user.mailbox.inbox.page(params[:page]).per(10)
      end 
       add_crumb 'Messages Received', messages_received_path
  
       @box = 'inbox'
       render :index
    end
  </code></pre>
  
  <p>UPDATE:<strong><em>_</em>__<em>_</em>__<em>_</em>__<em>_</em>__<em>_</em>__<em>_</em>__<em>_</em>__<em>_</em>__<em>_</em>__<em>_</em>__<em>_</em></strong></p>
  
  <p>assets/javascript/refresh_messages_count.js</p>
  
  <pre><code>$(document).ready(function () {
      // will call refreshPartial every 3 seconds
      setInterval(refreshPartial, 3000)
  
  });
  
  function refreshPartial() {
    $.ajax({
      url: "messages/refresh_part";
   })
  }
  </code></pre>
  
  <p>messages_controller.rb</p>
  
  <pre><code>def refresh_part
      @message_count = current_user.mailbox.inbox(:read =&gt; false).count(:id, :distinct =&gt; true)
  
      # get whatever data you need to a variable named @data 
      respond_to do |format| 
          format.js {render :action=&gt;"refresh_part.js"} 
      end
  
  end
  </code></pre>
  
  <p>views/layouts/_menu.html.erb</p>
  
  <pre><code>&lt;span id="message_received_count"&gt;&lt;%= render :partial =&gt; "layouts/message_received_count" %&gt;&lt;/span&gt;
  </code></pre>
  
  <p>views/layouts/_message_received_count.html.erb</p>
  
  <pre><code>&lt;% if user_signed_in? &amp;&amp; current_user.mailbox.inbox(:read =&gt; false).count(:id, :distinct =&gt; true) &gt; 0 %&gt;
   &lt;li&gt;&lt;%= link_to sanitize('&lt;i class="icon-envelope"&gt;&lt;/i&gt; ') + "Received" + sanitize(' &lt;span class="badge badge-info"&gt;'+@message_count.to_s+'&lt;/span&gt;'), messages_received_path  %&gt;&lt;/li&gt;
  &lt;% else %&gt;
   &lt;li&gt;&lt;%= link_to sanitize('&lt;i class="icon-envelope"&gt;&lt;/i&gt; ') + "Received", messages_received_path  %&gt;&lt;/li&gt;
  &lt;% end %&gt;
  </code></pre>
  
  <p>views/messages/refresh_part.js.erb</p>
  
  <pre><code>$('#message_received_count').html("#{escape_javascript(render 'layouts/messages_received_count', data: @message_count)}");
  </code></pre>