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

Form input using the div element (when clicked)

I am currently working on a page that connects to a database with user information. For each user, I am creating a separate div element so that there are 6 divs total (each representing a different user). My goal is to have the ability for a user to click ...

I am interested in altering the color of table rows using either JQuery or CSS

Looking to update row colors based on grouping. For example: Color the TR accordingly for every 5 rows: First 5 rows in green (0-4 Rows), Next five rows in red (5-9 Rows), Following five rows in yellow (10-14 Rows) and repeat the pattern... ...

Restarting the timer in JavaScript

How can I reset the countdown timer every time a user types into an input field? I tried using clearTimeout but it doesn't seem to work. Can anyone help me with my existing code instead of providing new code? DEMO: http://jsfiddle.net/qySNq/ Html: ...

Polymer event / callback for appending new child nodes

My current project involves creating a custom element, let's call it <parent-element>, that performs specific actions based on the presence of its childNodes. When I define the element like this: <parent-element> <div> </div&g ...

Struggling to integrate a JavaScript sdk with an Angular2 application due to missing dependencies

I've been struggling to incorporate the Magic: The Gathering SDK library into my Angular2 application. I've tried various methods, but nothing seems to work seamlessly. When I attempt to import the library using TypeScript like this: import { } ...

PHP not receiving data from jQuery Ajax (POST) request

Below is an Ajax function that sends data from a page to the same page for interpretation by PHP. When using Firebug, it is observed that the data is being sent, but not received by the PHP page. However, if we switch to a $.get function and retrieve the ...

Content that is dynamically generated by a database

I have been working on creating a unique wall feature for my website, inspired by Facebook. My aim is to allow users to submit form data and have it validated before storing it in a database. Additionally, I want this stored data to be displayed in a desig ...

How can we effectively transfer a value from TypeScript/Angular?

I am new to TypeScript and Angular, and I'm struggling with assigning a value to a variable within a function and then using that value outside of the function. In regular JavaScript, I would declare the variable first, define its value in the functio ...

Creating a callback function within stored procedures using JavaScript Language Integrated Query in documentDB: A step-by-step guide

According to the documentation, the code snippets below are considered equivalent. However, I have observed that in the first case, I am able to perform operations on multiple documents within the callback function, whereas the map function in the latter s ...

Using axios with async/await to handle unresolved promises in Javascript

I'm facing a challenge with a piece of code I've been working on. Despite my efforts to find a solution online, I haven't had any success so far. Here is the code snippet in question: const fetchSidebarData = async () => { let da ...

Exploring ways to validate the existence of a class in HTML table elements

If I want to verify if each element has a specific class when creating tables and clicking on the corresponding cells above them, This is what I have tried. However, it did not work as expected. How can I make this work correctly? What am I missing her ...

What is the best way to create a "check all" feature in React using child components?

I have come across a few questions here that somewhat address the issue, select all managed state of controlled checkboxes but none of them provide a solution for rendering a component with a checkbox. What I want is something like this, render: funct ...

Customizing Material UI Select for background and focus colors

I am looking to customize the appearance of the select component by changing the background color to "grey", as well as adjusting the label and border colors from blue to a different color when clicking on the select box. Can anyone assist me with this? B ...

Organizing pictures by category

I am currently working on creating an interactive image gallery with sorting options based on different categories such as land, sea, animals, and more. I have created a small example to demonstrate my concept. My objective: is to allow users to select a ...

Tips for transforming a nested for-loop into a recursive function

Trying to work with Memcached data in Node.js is proving to be a challenge due to the asynchronous nature of the language. My goal is to store all retrieved results in an object. This is how I would typically approach it: for( x = startX; x <= endX; x ...

Press one button to activate another button

I am looking to activate a button's class by clicking on another button. The button I have is: <button class="clear-cart banner-btn">clear cart</button> This button is used for clearing a cart. On the order confirmation page, I click on ...

Looking to retrieve the value of a selected checkbox within a horizontally laid out HTML table

Trying to extract values from a table with a horizontal header when checkboxes are selected. The goal is to retrieve the values of the selected column for all rows. Code snippet provided below. <script src="https://ajax.googleapis.com/ajax/libs/jquer ...

Dealing with the 'routes not found' error in a Node.js Express application (troubleshooting)

Attempting to address potential missing router errors in my app.js or router file has been a challenge for me. (various solutions found on Stack Overflow have not provided the correct resolution) The current state of my app.js or router files is functiona ...

Display the modal in Angular 8 only after receiving the response from submitting the form

I am encountering an issue where a pop-up is being displayed immediately upon clicking the submit button in Angular 8, before receiving a response. I would like the modal to only appear after obtaining the response. Can someone assist me with achieving thi ...

What is the method for retrieving embedded JavaScript content?

In an attempt to scrape a website using Cheerio, I am facing the challenge of accessing dynamic content that is not present in the HTML but within a JS object (even after trying options like window and document). Here's my code snippet: let axios = ...