I made chat system in my web application.
It’s basic chat with input field with messages.
I only wrapped messages_section then I’m using setInterval to load it partially and every 1 sec.
However, I found weird behaivor here.
When I’m typing something into input field, typed words get entered somehow when every time setInterval is loaded.
Now it seems that this is only affecting to browsing with FireFox:(
I was supposing setInterval wouldn’t affect to input field unless input field is set within
These are my codes. I want to know why and how to fix
jQuery
<script type="text/javascript">
//<![CDATA[
jQuery(document).ready(function () {
refreshPartial();
setInterval(refreshPartial, 1000)
});
function refreshPartial() {
$.ajax({
url: "/communities/setinterval_part?page=",
type: "GET",
dataType: "script",
});
}
//]]>
</script>
HTML
<form accept-charset="UTF-8" action="/communities/new_comments" class="new_comment" data-remote="true" id="new_comment" method="post">
<input class="chat" id="input" name="comment[body]" type="text" />
<button type="submit" class="btn">submit</button>
<form>
<span id="messages_section">
here comes messages!
</span>
setinterval_part.js.erb
$('#messages_section').html("<%= j(render(:partial => 'communities/comment')) %>");
<% if @post %>$('#body_input').val('');<% end %>
communities_controller.rb
def setinterval_part
@comments = @community.comment_threads.order("updated_at DESC").page(params[:page]).per(@number_of_comments_to_display)
@comment = @community.comment_threads.build
respond_to do |format|
format.js
end
end
First of all I recommend you do not use setInterval in this case. What if your server will take more than 1 second to answer to client? I think that you can run
refreshPartial()function right from yoursetinterval_part.js.erb.So you need to make this changes to JS-part in the view:
And this to
setinterval_part.js.erb: