Something is not quite right when the page is loading in a Ruby on Rails application

In the process of developing a wiki clone, I am faced with an issue involving JavaScript. When I navigate to a specific page by clicking on a link, the JavaScript does not function properly until I refresh the page. The JavaScript aspect mainly involves an autocomplete search feature that displays user names matching the input in the search box at the bottom of the page.

One of the features in my app is a link on the show#wikis view that redirects users to the edit#wikis view through the following code snippet:

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

However, when this link is clicked and the edit#wikis page loads, the JavaScript and AJAX calls cease to work. Below is the views/wikis/edit.html.erb page which contains the form partial for collaborators:

<h1>Edit Wiki</h1>

 <div class="row">
   <div class="col-md-4">
     <p>Guidelines for Wikis</p>
     <ul>
       <li>Make sure it rhymes.</li>
       <li>Avoid using the letter "A".</li>
       <li>Excessive hashtags will result in being 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 as follows:

<%= 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%>

The relevant JavaScript code can be found in the file

assets/javascripts/collaborations.js.erb
:

$(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 responsible for handling the AJAX calls is collaboration_search within

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 attempted to resolve the issue by removing the turbolinks gem without success. Any assistance in resolving this problem would be greatly appreciated!

Answer №1

I'm uncertain why your JavaScript isn't functioning properly on the first try. There could be several reasons for this, with Turbolinks often being a common suspect. To better understand the issue, consider trying the following steps:

  • Insert a console.log('in here'); statement in your JS file within the document ready function. If it appears in the Web Inspector console upon loading, it indicates whether the file is loading but not executing correctly, or if it's not loading at all.

  • Check for any JavaScript errors highlighted in red in the Web inspector.

  • Another possibility is an error related to how you're combining JS and ERB. A .js.erb file usually combines JavaScript functionality within a view. Ensure it is placed in the app/views directory and handled correctly by your controller. Confirm where and how you are including it, either in the application.js file or in the <head> tag of your layout.html.erb view.

Regarding the use of ERB in the file, it seems unnecessary. In fact, the line <% @user = "data" %>; overwrites the Ruby/Rails variable @user with the string "data", potentially causing issues. Consider renaming the file to .js, verifying its inclusion in application.js, adding a console.log to confirm loading, checking for JS errors, and removing the unnecessary ERB line to troubleshoot effectively.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a method similar to Ruby's .methods in Python?

Transitioning from Ruby to Python, I find myself missing the simplicity of being able to view a list of all the methods available for a specific object in the shell. Does Python have a feature similar to Ruby's Object#methods to achieve this? ...

How to set a default option in a dropdown menu using Angular 4

Many questions have been raised about this particular issue, with varying answers that do not fully address the question at hand. So here we go again: In my case, setting the default value of a dropdown select by its value is not working. Why is that so? ...

Having trouble deciphering and showing chunked image data received from the server

How can I display an image received in chunked encoding from an ajax call to the server on the client side? Here is my code: $.ajax({ url: service url, type: 'POST', headers: { "accept": "image/jpeg", ...

Ways to prevent a div from loading an HTML page

When an external button is clicked, the remove() function on id main is triggered. The issue arises when a user quickly clicks on btn1 and then presses the external button, causing the removal to occur before the event handler for btn1. This results in the ...

Is your webpage slow to respond after a page-refresh? (Delayed HTML rendering causing lag)

Whenever I adjust the screen size to that of a phone or any device smaller than 768px, the search bar doesn't display in its proper position until the page is refreshed. It should be correctly placed right from the start. Furthermore, when I resize th ...

When a URL is entered, information is not retrieved from the database

I have a simple app setup where the data (iPhones from the database) is fetched in the AppComponent itself. ngOnInit(): void { this.iphoneservice.fetchIphones(); } The fetchIphones method is located in my iPhoneService file and consists of 3 functio ...

JSON does not send information to the specified web address

Attempting to send some data to the following URL: " $(function() { var frm = $(document.myform); var data = "?lm_po_id=154668&authentication=ThisisAuth&description=ThisIsDesc";//JSON.stringify(frm.serializeArray()); ...

After the jquery.show function is executed, an unexpected WebDriverException occurred, indicating an unknown error that prevents focusing

Here is my line of JavaScript code: $('#name').show(); And this is my webdriver code line: wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("name"))).sendKeys("Some Name"); When running the test, I encountered an exception: Web ...

Images are not being shown by Glide JS

I have implemented the Glide JS carousel within a VueJS project to showcase multiple images, however, I am encountering an issue where only the first image is being displayed. The <img/> tag has the correct src URL for all three images, but only th ...

Hiding the keypad on an Android device in an Ionic app when user input is detected

I am currently utilizing the syncfusion ej2 Calendar plugin for a datepicker, but I am only using options such as selecting ranges like today, 1 month, or last 7 days from the plugin itself. The plugin provides dropdown options when the calendar is trigger ...

Conceal the option to "show more" when there are no additional posts to display

Is there a way to dynamically hide the load button when no more posts are available? I've included my code below: function.php function load_more_posts_ajax(){ $offset = $_POST["offset"]; $ppp = $_POST["ppp"]; header("Content-Type: tex ...

Adapting the column width to display or hide content with CSS styling

I have a row with 2 columns. The left column contains my main content and the right column is a chatroom. I would like users to be able to minimize and open the chatroom, which I already know how to do. However, when the chatroom is open, I want the left ...

CSS fixed dynamically with JavaScript and multiple div elements placed randomly

Is it possible to dynamically change the position of multiple div elements on a webpage without reloading? I am looking for a way to modify the top and left positions of several divs, all with the same class, simultaneously. I want each div to have a diff ...

Distribute the capabilities of the class

Is there a way to transfer the functionalities of a class into another object? Let's consider this example: class FooBar { private service: MyService; constructor(svc: MyService) { this.service = svc; } public foo(): string { ...

Working with Angular to add various items to an array based on multiple conditions

Currently, I am a beginner in TypeScript and currently involved in an Angular project. As part of my work, I need to make an API call and perform various operations on the received data: public data_Config: IConfig[] = []; this.getService.Data(input).sub ...

To reveal the secret map location, just tap on the button - but remember, this only applies to

I am encountering an issue with duplicating a card and toggling the hidden location map. Currently, the location button only works for the first card and not for the rest. I need each card to independently open and hide the location map when clicked on the ...

Tips for utilizing window.scrollTo in tandem with react/material UI?

I have a simple functional component that displays an alert panel with an error message under certain conditions. The issue I am facing is that when the alert panel is rendered due to an error, it might be off-screen if the user has scrolled down. To addre ...

Discovering a method to detect clicks outside of a React functional component

Looking to identify when a click occurs outside of a React functional component. After stumbling upon an article, I followed the provided code but unfortunately, it didn't work as expected. Despite identifying the issue, I am still searching for a so ...

What is the best way to transfer the userId from the browser to protractor?

Using *ngFor in my angular2 component to render users has been successful. <ul> <li *ng-for="let user of users"> <input [(ng-model)]="user.name"> <button (click)="remove(user._id)">Remove</button> ...

Angular2: the setTimeout function is executed just a single time

Currently, I am working on implementing a feature in Angular2 that relies on the use of setTimeout. This is a snippet of my code: public ngAfterViewInit(): void { this.authenticate_loop(); } private authenticate_loop() { setTimeout (() =& ...