Enhance your Rails 5 application with a dynamic live search feature powered by Keyup. Say goodbye to

Currently, I have a Rails 5.1.3 application with a simple contact model that stores names and phone numbers. To enable searching within the index view/page, I am utilizing Ransack. A keyup event listener written in Coffeescript captures user input as they type. While it seems to be functioning correctly (as per the Rails dev logs), the input form loses focus and the partial does not refresh when clicking back into the input field to continue typing. This issue leads me to believe there might be a problem with Turbolinks integration, although I cannot definitively confirm.

Shown here is an excerpt from my controller: contacts_controller.rb

class ContactsController < ApplicationController

  def index
    @q = Contact.ransack(params[:q])
    @contacts = @q.result(distinct: true).order("name asc").paginate(:page => params[:page], :per_page => 2)
    respond_to do |format|
      format.html
      format.js  {render "index", :locals => {:contacts => @contacts}}
    end
  end
end

Below is the content of my index view file index.html.erb

<%= link_to "New Contact", '#contact-modal', data: {toggle: "modal", target: "#contact-modal" }, class: 'btn btn-info btn-sm'  %>
<%= render 'shared/contact_modal' %>
<div id="search">
  <%= render 'contacts/search' %>
</div>

<div id="results">
  <%= render 'contacts/results', contacts: @contacts %>
</div>

Here is my JS file named index.js.erb

$("#search").html("<%=j render :partial => 'contacts/search' %>")
$("#results").html("<%=j render :partial => 'contacts/results', locals: {contacts: @contacts} %>")

The following showcases the search and results partials:

 <%= search_form_for(@q, url: "/contacts", method: :get, id: "contacts_search", remote: true) do |f| %>
  <%= f.search_field :name_or_address_or_office_number_or_home_number_or_mobile_number_or_fax_number_or_email_or_misc_info_cont, placeholder: 'Search...', class: 'form-control' %>
  <%= f.submit %>
<% end %>



 <table class="table table-striped">
  <thead class="thead-default">
    <tr>
      <th>Name</th>
      <th>Company Name</th>
      <th>Office Number</th>
      <th>Mobile Number</th>
      <th>Home Number</th>
      <th>Address</th>
      <th>Email</th>
    </tr>
  </thead>
  <tbody>
    <% contacts.each do |contact| %>
    <tr>
      <td><%= link_to "#{contact.name}", contact_path(contact) %></td>
      <td><%= contact.company_name %>
      <td><%= contact.office_number %></td>
      <td><%= contact.mobile_number %></td>
      <td><%= contact.home_number %></td>
      <td><%= contact.address %></td>
      <td><%= contact.email %></td>
    </tr>
    <% end %>
  </tbody>
</table>
<%= will_paginate contacts, renderer: WillPaginate::ActionView::BootstrapLinkRenderer %>

Within the contacts.coffee file, you can find the following code snippet:

$(document).on 'turbolinks:load', ->
  $('#contacts_search input').keyup ->
    $.get $('#contacts_search').attr('action'), $('#contacts_search').serialize(), null, 'script'
    false

I'm referencing a portion of the development.log, which displays the function triggering appropriately. However, the partial fails to refresh entirely. Specifically, it handles one keystroke before halting and losing focus on the input field altogether.

Any insights into what might be causing this interruption or if there's an error within my Coffeescript would be greatly appreciated.

 Started GET "/contacts?utf8=%E2%9C%93&q%5Bname_or_address_or_office_number_or_home_number_or_mobile_number_or_fax_number_or_email_or_misc_info_cont%5D=a&_=1504386143674" for 127.0.0.1 at 2017-09-02 16:02:25 -0500
Processing by ContactsController#index as JS
  Parameters: {"utf8"=>"✓", "q"=>{"name_or_address_or_office_number_or_home_number_or_mobile_number_or_fax_number_or_email_or_misc_info_cont"=>"a"}, "_"=>"1504386143674"}
  User Load (0.3ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 7], ["LIMIT", 1]]
  Role Load (0.1ms)  SELECT  "roles".* FROM "roles" WHERE "roles"."name" = $1 LIMIT $2  [["name", "disabled"], ["LIMIT", 1]]
  Role Load (0.1ms)  SELECT  "roles".* FROM "roles" WHERE "roles"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
  CACHE Role Load (0.0ms)  SELECT  "roles".* FROM "roles" WHERE "roles"."name" = $1 LIMIT $2  [["name", "disabled"], ["LIMIT", 1]]
  Rendering contacts/index.js.erb
  Rendered contacts/_search.html.erb (1.4ms)
  Contact Load (0.7ms)  SELECT  DISTINCT "contacts".* FROM "contacts" WHERE ((((((("contacts"."name" ILIKE '%a%' OR "contacts"."address" ILIKE '%a%') OR "contacts"."office_number" ILIKE '%a%') OR "contacts"."home_number" ILIKE '%a%') OR "contacts"."mobile_number" ILIKE '%a%') OR "contacts"."fax_number" ILIKE '%a%') OR "contacts"."email" ILIKE '%a%') OR "contacts"."misc_info" ILIKE '%a%') ORDER BY name asc LIMIT $1 OFFSET $2  [["LIMIT", 2], ["OFFSET", 0]]
   (0.3ms)  SELECT COUNT(DISTINCT "contacts"."id") FROM "contacts" WHERE ((((((("contacts"."name" ILIKE '%a%' OR "contacts"."address" ILIKE '%a%') OR "contacts"."office_number" ILIKE '%a%') OR "contacts"."home_number" ILIKE '%a%') OR "contacts"."mobile_number" ILIKE '%a%') OR "contacts"."fax_number" ILIKE '%a%') OR "contacts"."email" ILIKE '%a%') OR "contacts"."misc_info" ILIKE '%a%')
  Rendered contacts/_results.html.erb (3.7ms)
  Rendered contacts/index.js.erb (9.6ms)
Completed 200 OK in 32ms (Views: 25.8ms | ActiveRecord: 1.6ms)

Answer №1

Initially, the JavaScript function was causing the search form partial to reload. To fix this issue, I made the following adjustment:

$("#search").html("<%=j render :partial => 'contacts/search' %>")
$("#results").html("<%=j render :partial => 'contacts/results', locals: {contacts: @contacts} %>")

After changing it to this:

$("#results").html("<%=j render :partial => 'contacts/results', locals: {contacts: @contacts} %>")

The problem was resolved and everything now works flawlessly.

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

Use jQuery to switch back and forth between the login and registration forms on a single

I've set up two forms, one for login and one for registration, with the default view showing the login form. There's a link that says "Don't have an account?" and when it's clicked, the registration form will display while the login for ...

Remove duplicate elements from a JSON array

How can I add each item in an array for each duplicate? Transform: [ { "uuid":"EE877ABD-932F-4B4C-AB23-B324363B0B60", "planning":[ { "uuid":"6D680178-9B05-4744-A004-163D4B3E1E84", "star ...

Angular 6 and the intricacies of nested ternary conditions

I need help with a ternary condition in an HTML template file: <div *ngFor="let $m of $layer.child; let $childIndex=index" [Latitude]="$m.latitude" [Longitude]="$m.longitude" [IconInfo]="$childIndex== 0 ? _iconInfo1:$c ...

Calculate the difference and sum of time values with varying signs in JavaScript

-12:00 - 5:30 => -6:30 -2:00 - 5:30 => 3:30 00:00 - 5:30 => -5:30 6:00 - 2:30 => 3:30 I am interested in subtracting time with both positive and negative indices. let myCountries = [ { countryName: "NewZealand", ...

Issue: Module '/Users/MYNAME/Desktop/Projects/MYPROJECTNAME' not found

I am currently in the process of compiling Node using TypeScript, and I'm still getting acquainted with it. An issue I encountered was that my /src files were not being updated when I made changes and restarted the server. To troubleshoot, I decided ...

Exploring ways to loop through a JSON array and embed it into an HTML element

After the ajax request, the data returned is structured as follows: Data = [ ["18/02/2019", "A"], ["19/03/2019", "B"], ["21/05/2019", "C"], ] The ajax request was successful and the data is stored in a variable named Data within a function. ...

Issue specifically with Android 6 WebView - jQuery 1.9.1 where a RangeError is thrown due to the call stack size being exceeded

An error message "Uncaught RangeError Maximum call stack size exceeded" is causing a web application to fail in the jQuery-1.9.1 extend() function, but strangely it only occurs on Android 6. The application runs smoothly on all other platforms such as Des ...

The script file (.js) isn't showing up on the PHP or HTML webpage

Experiencing a peculiar issue and seeking advice on alternative solutions due to my limited experience in this matter. The Issue: I currently have the following script running smoothly: <script type="text/javascript" id="myscript" src="http://piclau ...

Looping through Jquery Ajax requests

Currently, I am developing a SQL converter that converts MySQL to MongoDB. The user interface for this converter is being created with the help of Ajax. Ajax is crucial for handling large conversions. Due to the limitations of MySQL select code, the conve ...

"Utilizing GroupBy and Sum functions for data aggregation in Prisma

I am currently working with a Prisma schema designed for a MongoDB database model orders { id String @id @default(auto()) @map("_id") @db.ObjectId totalAmount Int createdAt DateTime @db.Date } My ...

Should FormBuilder be utilized in the constructor or is it considered a poor practice?

section, you can find an example of implementation where declarations for formBuilder and services are done within the constructor(). While it is commonly known that using services inside the constructor() is not a recommended practice and should be done ...

nested sequential ajax calls

I am attempting to run a couple of functions with ajax calls inside them in sequence. However, I cannot execute them asynchronously as they both start simultaneously. Here is my code: function engine_start() { a1(); a2(); } a1() { $.ajax( ...

Incorporating Angular to dynamically fetch data through AJAX and fill in content post-page render

As a backend API developer diving into AngularJS (version 1) for the first time with my current project, I have encountered a scenario that requires me to fetch server-side content dynamically post-render. The page is set up with ng-app="app" in the <ht ...

What could be causing this JavaScript code not to run?

Help needed! I'm a student struggling to diagnose the issue in my code. Whenever I click the buttons, nothing happens at all. I've tried debugging by isolating each function, but still can't seem to figure it out. I've searched through ...

Selenium: The function moveToElement is not valid for the driver.actions() method

After creating all my tests using Selenium IDE, I decided to export them to JavaScript Mocha for running in travis. While the tests run smoothly in Selenium IDE and can be exported, I encountered an issue when trying to run them which resulted in the erro ...

Error encountered: The Jquery-ui functionality ceases to operate upon the completion of content

I'm utilizing the jQuery UI library to rearrange the items on my list. Initially, everything works smoothly without any issues. However, when I navigate to another page and then return to the page with my list, I encounter difficulties. It's wor ...

Connecting the table and chart based on the selection made in the dropdown menu

I have a scenario where I need to display 5 tables, 2 charts, and a drop-down menu. The challenge is to bind all these elements based on the selection from the drop-down using AJAX. <select id="userclicked"> <?php foreach($model["combouser"] as & ...

Access Images from Server using Front-End Technology

I have a collection of images stored in a server folder that I want to display on a div element using client-side code. Initially, I tried to achieve this with AJAX, but it returned raw data instead of the image URL. Despite my efforts to find a solution, ...

What is the best way to effectively incorporate Ruby into the CSS attribute of a HAML %li element?

Greetings everyone, I am new to the world of development and seeking guidance from experienced individuals. I have been trying to solve a coding issue for quite some time now. I am currently enrolled in a programming course at Code Academy based in Chicago ...

Transferring user-selected values from JavaScript to a PHP file

When sending values from JavaScript to a PHP file, everything works smoothly when all the values are collected. Step1 functions perfectly as both fields are mandatory. However, in Step2, values are only sent when all the fields are selected. There are co ...