简体   繁体   中英

javascript issue on page load with ruby on rails application

background: I am creating a wiki clone with users that can create wikis. The users can also add collaborators which are fellow users to contribute to the wikis.

I am having trouble with the the javascript when I get to that page by clicking a link. When I re-load this same page the javascript works. Most of the javascript is for an autocomplete search function that renders names of users at the bottom of the page that matches the letters being typed into the search box.

Within my functionality I have a link on the show#wikis view that links to the edit#wikis view which looks like this:

 #views/wikis/show.html.erb
 <%= link_to "Edit", edit_wiki_path(@wiki), class: "btn btn-success" %>

Once the link is clicked and the edit#wikis page appears the page loads but the javascript and ajax calls do not work. The views/wikis/edit.html.erb page is below, however the important part of the code where most of the ajax is being used is the form partial for collaborators at the bottom:

    <h1>Edit Wiki</h1>

 <div class="row">
   <div class="col-md-4">
     <p>Guidelines for Wikis</p>
     <ul>
       <li>Make sure the it rhymes.</li>
       <li>Don't use the letter "A".</li>
       <li>The incessant use of hashtags will get you banned.</li>
     </ul>
   </div>
   <div class="col-md-8">
     <%= form_for @wiki do |f| %>
       <div class="form-group">
         <%= f.label :title %>
         <%= f.text_field :title, class: 'form-control', placeholder: "Enter post title" %>
       </div>
       <div class="form-group">
         <%= f.label :body %>
         <%= f.text_area :body, rows: 20, class: 'form-control', placeholder: "Enter post body" %>
       </div>
       <%if policy(@wiki).edit_form_settings? %>
         <div class="form-group">
          <%= f.label :public, class: 'checkbox' do %>
            <%= f.check_box :public %> Public wiki
          <% end %>
        </div>
      <% end %>
       <div class="form-group">
         <%= f.submit "Save", class: 'btn btn-success' %>
       </div>
     <% end %>
   </div>
 </div>
<%if policy(@wiki).edit_form_settings? %>
 <%= render partial: "collaborations/new", locals: { wiki: @wiki, collaboration: @collaboration} %>
<% end %>

The form partial from views/collaborations/_new.html.erb is listed below:

<%= form_for [wiki, collaboration] do |f|%>

<div class = "col-md-8">

    <div class = "form-group">
      <%= f.label :user_name %>
      <%= f.text_field :user_name, class: 'form-control', placeholder: "Enter name"  %>
    </div>
    <%= f.hidden_field :user_id %>
    <div class = "form-group">
      <%= f.submit class: 'btn btn-success' %>
    </div>
  </div>

    <div id="user_data" class="dropdown">
  <ul class="list-group" style= "width:50%">
    <!-- <li class="list-group-item">Cras justo odio</li>
    <li class="list-group-item">Dapibus ac facilisis in</li>
    <li class="list-group-item">Morbi leo risus</li>
    <li class="list-group-item">Porta ac consectetur ac</li>
    <li class="list-group-item">Vestibulum at eros</li> -->
  </ul>
</div>

</div>

  </div>

</div>
<%end%>

I have the javascript in the assets/javascripts/collaborations.js.erb file:

$(document).ready(function()
{


     $('#collaboration_user_name').on('keyup', function() { 

      text = $(this).val();
      // alert(text);

      $.ajax({ url: "/collaborations?collaboration="+text, 
        beforeSend: function( xhr ) { 
          xhr.overrideMimeType( "text/plain; charset=x-user-defined" ); 
        } 
      }).done(function( data ) {
        console.log( "data:", data ); 
        users = JSON.parse(data);

        $("#user_data ul li").remove();
        $.each( users, function( index, value ) {
          $("#user_data ul").append("<li class='list-group-item' value ="+ users[index].id+">"+users[index].name+ ", " +users[index].email+ "</li>"); 
        });
      <% @user = "data" %>;
        $("#user_data").append(JSON.parse(data).name);
        $(' .list-group-item').click(function() {
        //alert( $(this).val() );
            $('#collaboration_user_name').val($(this).text().split(",")[0]);
           $('#collaboration_user_id').val($(this).val());
      });
    });
 });


});

lastly the controller action that the ajax calls is collaboration_search in controllers/collaborations_controller.rb :

class CollaborationsController < ApplicationController
  respond_to :html, :js
def collaboration_search
     #name_search = params[:collaboration][:user_name].to_s
     @users_by_name = User.where('name Like ?', "%#{params[:collaboration]}%").limit(4)
     puts @users_by_name.to_a
      render json: @users_by_name
  end
end

I have tried removing the turbolinks gem but that hasn't fixed the problem. I would appreciate any help!

I'm not 100% sure why your JS isn't working the first time around. There could be many culprits, of which Turbolinks is often a good first guess. But I think you could get closer to discovering what's going on by trying some of the following:

  • Throw a console.log('in here'); in your JS file, right within the document ready. When it's loaded, that should print to the Web Inspector console. This will help you decipher whether the file is loading (but not running correctly) or just not loading at all.

  • Make sure there aren't any JS errors. These would show up in red in the Web inspector.

  • One error or weirdness might result from the way you're combining JS and ERB. A .js.erb file is generally essentially a view with combined JavaScript functionality. You'd generally keep it in the app/views directory, and tell your controller how to handle it. In this case, this looks like more or less a regular JS file -- in which case how you include it is the question that has the greatest effect on its function. Are you including it in your application.js file? In the <head> tag of your layout.html.erb view? Some other way?

In relation to the ERBness of this file, it's worth pointing out that you don't seem to need the ERB at all. If anything, your use of ERB is potentially messing things up. The only ERB-like line I see is this one:

<% @user = "data" %>;

That line takes the Ruby/Rails variable @user and overwrites it with the string "data". That's almost certainly something you don't want to do. (I'm unsure whether it will actually affect the variable, as you use it here.)

tl;dr -- I'd rename the file .js , make sure it's included in application.js , and add a console.log to the file to make sure that it's getting loaded, so you can isolate whether it's a loading issue or a JavaScript issue. Also, check for JS errors, and remove the <% @user = "data" %> line. Hopefully the above will get you closer to figuring out what's going on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM