Utilizing Typeahead in a Rails application: Implement the feature to add JSON requests to a single designated request rather than applying it to all requests through prefetching

The type ahead feature is functioning correctly in its intended location. However, there is an issue where the JSON request for the data is being made on every request rather than just one specific request.

This is the controller I am using:

#controllers/agencies_controller.rb
class AgenciesController < ApplicationController

  def get_unique_agency_names
    @unique_agency_names = Agency.uniq.pluck(:name)
    respond_to do |format|
      format.json { render json: @unique_agency_names }
    end
  end
  ...
end

Below is the script section from my JavaScript file:

#app/assets/javascripts.agencies/index.js
$(document).ready(function(){
  /* For typeahead functionality on name input of search form for agencies */
  var agency_names = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.whitespace,
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    prefetch: '../agencies/get_unique_agency_names.json'
  });

  $('#prefetch .typeahead.name_input').typeahead(null, {
    name: 'agency_names',
    source: agency_names
  });
});

For reference, here is where I want this functionality to take place: Within this form:

# just showing the relevant part of the form
<div class="form-group" id="prefetch">
  <%= f.label :name_cont, "Agency Name" %>
  <%= f.text_field :name_cont, class: "form-control typeahead name_input", placeholder: "Enter Agency Name" %>
</div>

This is the relevant route in config/routes.rb:

resources :agencies do
  collection do
    get 'get_unique_agency_names'
  end
end

I need to ensure that the

GET "/agencies/get_unique_agency_names"
request only occurs when specifically required. Currently, it appends this JSON request to every single request, which is not the desired behavior. The intention is for the JSON request to be triggered only for a particular request.

View Twitter's Type Ahead Examples for more information.

Answer №1

Here is a solution that might help

  $('#prefetch .typeahead.name_input').typeahead(null, {
    generateOnLoad:false,
    name: 'agency_names',
    source: agency_names
  });

generateOnLoad {boolean}

null (default)

If you enable this option, the source data will be generated on page load instead of waiting for user input.

Note: This option may not work well with dynamic: true unless other configurations are adjusted.

Additionally, if you notice the rails manifest file adding your call to every page, ensure to verify element existence before binding type ahead:

if($('#prefetch .typeahead.name_input').length){
      $('#prefetch .typeahead.name_input').typeahead(null, {
        generateOnLoad:false,
        name: 'agency_names',
        source: agency_names
      });
}

Answer №2

Instead of strictly enforcing a single request, I recommend implementing a strategy to manage and limit requests when dealing with a large data set. Utilize Bloodhound’s prefetch option to cache data, and leverage the sufficient and remote options to control and optimize JSON file requests. Adjust Typeahead’s minLength option as a safeguard measure.

Prefetching can assist by using the browser's local storage for caching, although it has its limitations particularly with large datasets where only a portion may be cached initially.

Remote functionality is essential post-initialization, allowing you to manage requests by debouncing or throttling them effectively. Utilize parameters like url, rateLimitBy, and rateLimitWait within the remote configuration options. Additionally, Bloodhound will use remote to back-fill missing data if the specified number of sufficient datums are not met.

Lastly, avoid passing null values and adjust the minLength parameter on your Typeahead constructor to a value greater than the default of 1. This adjustment helps prevent excessive lookups in your dataset, while ensuring the minLength value is shorter than your smallest possible result length.

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

Fetch several images simultaneously from a photo collection using JavaScript by generating a batch process

I need help with creating an image gallery that allows users to download multiple images by selecting them. The download should result in a zip file. I have checkboxes for selecting the images, but I'm struggling to figure out how to enable the downlo ...

What is an alternative way to rewrite this regular expression without relying on the deprecated API?

My JavaScript code uses a regular expression, myRegexp, to match numbers in a string: var myRegexp = new RegExp('[0-9]+'); The code then extracts numbers from the string and returns an array: var string = '123:456'; var nums = []; wh ...

Cannot find the appended element in an AJAX call using jQuery

Within the code snippet, .moneychoose is described as the div in moneychoose.jsp. Interestingly, $(".moneychoose") cannot be selected within the ajax call. $("input[name='money']").on("click", function() { if ($("#money").find(".moneychoose" ...

Refreshing a single HTML element in ASP.NET MVC - the simple way!

Recently, I put together an image gallery using the unite gallery jquery plugin and now I want to change up the images it displays. My plan is to have a button labeled "art" that, when clicked, triggers a function to update the directory path and load ne ...

The image begins rotating only after the second click has been made

Having trouble with jQuery and rotation effects on an image? I have a solution for you. The image should rotate while toggling at the same time, but there's a twist - on the first click, it won't rotate but will still toggle. From the second clic ...

Collaborative session sharing between two node applications through Single Sign-On (SSO

I currently have a website created with express and node.js. I need to add a nodebb forum to this website, which is a separate node application. Both the main site and the forum use Facebook login, but users have to log in separately using the same Faceboo ...

Experiencing difficulties with parsing JSON data and storing values in a database

I received a JSON response from the server and need help saving the values in a MySQL database using PHP. Can someone please assist me with this? {"fields":[{"label":"Do you have a website?","field_type":"website","required":false,"field_options":{}," ...

Issue with IntersectionObserver not detecting intersection when the root element is specified

I am encountering an issue with my IntersectionObserver that is observing an img. It works perfectly when the root is set to null (viewport). However, as soon as I change the root element to another img, the observer fails to detect the intersection betwee ...

Display a sneak peek on a separate tab

I have an editor on my website where users can input and edit their own HTML code. Instead of saving this to a database, I want to display the current user's HTML code in a new window using JavaScript. How can I achieve this without storing the code p ...

When two $scopes are updated simultaneously, it leads to the duplication of data

Here is the snippet of code I am working with: $scope.addToOrder = function(index) { var tempItem = $scope.item; if (tempItem[index].validate == true){ if (_.isEmpty($scope.item2) == true) { $scope.item2.push ...

removing a specific cookie from the browser's cookies using jQuery

This block of code displays a URL along with a delete image for removing a cookie. The add and display functions are working fine, but I'm stuck on how to implement the delete function. function backLinks(){ var pathname = window.location; va ...

What is the most efficient method for storing values from multiple radioGroups in the state of a controlled component?

Just starting out with React, looking to build a multi-step form with a step counter in the State and Switch statement for component display. Following a tutorial on YouTube. Currently storing user input values in the state via props. The form includes a ...

A guide on how to automatically preselect a RadioGroup option in Material-UI

When a user selects an option from the MCQ Select using RadioGroup in my code and submits it, they should be able to return later and see the option they selected highlighted, similar to how Google Forms allows users to review their selections. Below is t ...

What is the best method to cache all backend data in Rails?

Can we cache all requests temporarily within the Rails backend? There are instances when it could be beneficial to work on frontend tasks without needing to wait for the backend to reload on the page. ...

Creating beautifully centered rows of three images dynamically

Seeking a way to dynamically generate centered rows of three images based on the quantity being loaded. The goal is to have one row for three images, two rows for four images, and four rows for ten images. Both the images and their container div are fixed ...

Guide on connecting various information to a jquery element through .data() within a custom plugin

I have come across a problem with my two plugins $.fn.expect = function (expectation) { return this.each(function () { $(this).data('expectation', expectation); }); } $.fn.isExpected = function () { return $(this).dat ...

Ways to Toggle div Visibility for Elements with Identical Class Names on an Individual Basis

After searching for solutions on stackoverflow, I attempted to implement some answers provided by other users, but I'm still not achieving the desired outcome. In my website's about section, there are four different items. When a specific item&a ...

I'm wondering if there is a specialized event for leaving the "select scroller" interface on iOS that is specific to vendors

Recently, I encountered a problem with iOS where tapping on a <select> box triggers the "scroll wheel" interface, pushing the modal being accessed upwards. While this behavior is acceptable, the issue arises when the modal fails to retain its origina ...

Dealing with a 409 conflict situation involving a document in Node.js using Nano library

After conducting research, it has come to my attention that there are numerous document conflicts with couchdb. While exploring a potential solution in Updating a CouchDB document in nano, I discovered the following steps: Retrieve the document Store th ...

Should I increase the number of followers, or opt for an aggregated method to monitor them?

My system loads products using an infinite scroll, displaying 12 at a time. Sometimes, I may want to sort these products based on the number of followers they have. Here's how I keep track of the followers for each product: The follows are stored i ...