1

This jQuery code should enable 2 actions.

1st action is auto-reloading page for every 7 seconds(refreshPartial();)
2nd action is auto input to chat_box field when a link is clicked.

2nd action works fine only if I remove 'refreshPartial();' from below.
Is it conflict error or something? How can I fix?

<% if current_user %>
    <% content_for(:head) do %>
        <%= javascript_tag do %>

            jQuery(document).ready(function () {

                 refreshPartial();

                 $('a#username').click(function() {
                     $(".chat_box#body_input").val($(this).attr('value'));
                 });

            });


            function refreshPartial() {
              $.ajax({
                url: "<%= show_user_path(@user) %>/refresh_part?page=<%= params[:page] %>",
                type: "GET",
                dataType: "script",
              });
            }

        <% end %>
    <% end %>
<% end %>

refresh_part.js.erb

$('#chat_comment').html("<%= j(render(:partial => 'users/comment')) %>");
setTimeout(refreshPartial,7000);

Controller

def refresh_part
    @comments = @user.comment_threads.order("updated_at DESC").page(params[:page]).per(10)
    @comment = @user.comment_threads.build

    respond_to do |format|
        format.js 
    end
end

View(Form input field)

<a name="comment_part"></a>
<form accept-charset="UTF-8" action="/users/John_Smith/comments" class="new_comment" data-remote="true" enctype="multipart/form-data" id="new_comment" method="post">
    <input name="utf8" type="hidden" value="&#x2713;" />
    <input name="authenticity_token" type="hidden" value="vvwHabqywaDXv0Sv5NrbPP5kfdwhfewovbHkegkOUm2/2uJdNs=" />
    <input class="chat_box" id="body_input" name="comment[body]" type="text" />  
    <button type="submit" class="btn">Submit</button>   
</form>
MKK
  • 2,713
  • 5
  • 31
  • 51

1 Answers1

2

I dont know ruby but i think this problem have been answered many times on Stackoverflow.

jquery-click-event-not-firing-on-ajax-loaded-html-elements

click-events-stop-working-after-an-ajax-load

jquery-event-not-working-after-ajax-pagination

Be aware that you should use .on() instead of .live() event because .live() is deprecated.

Community
  • 1
  • 1
adamnyberg
  • 58
  • 1
  • 8
  • Thanks for an answer:) So in my case, what should I replace with? – MKK Jun 16 '13 at 08:20
  • 1
    `$('a#username').click(function() { $(".chat_box#body_input").val($(this).attr('value')); });` should be: `$(document).on('click', 'a#username', function() { $(".chat_box#body_input").val($(this).attr('value')); });` – adamnyberg Jun 16 '13 at 08:28