Harnessing the Power of JSON in Rails to Enhance Your jQuery UI Autocomplete Form

In the context of a rails application, I have been exploring different methods to fetch data from a JSON file. Despite my efforts, I have not been able to find a solution that suits my requirements. The static data I have is quite extensive, consisting of around 8,000 lines, and it looks something like this:

    [
    {"web_page": "http://www.usjc.uwaterloo.ca/", "country": "Canada", "domain": "usjc.uwaterloo.ca", "name": "University of St. Jerome's College"},
    {"web_page": "http://www.ustanne.ednet.ns.ca/", "country": "Canada", "domain": "ustanne.ednet.ns.ca", "name": "St. Anne University"}
    ]

I have saved the above data in a JSON file named universitydata.json located in my apps/assets/javascripts folder.

Below is the JavaScript code snippet:

    function updateUniSearch() {
         $("#university-field").autocomplete({
                source: universitydata
            });
    }        

The Ruby file embeds the event for the `updateUniSearch()` function on keydown as follows:

    <%= f.text_field :university, :id => "university-field", :onkeydown=>"updateUniSearch()" %>

Let's assume I define `universitydata` like this:

   var universitydata = ["Maine", "Harvard"];

When typing 'm' in the autocomplete form, "Maine" appears as an option using the local array. However, when attempting the same with the data stored in universitydata.json file within my javascript assets folder, nothing happens. Am I implementing this incorrectly? Could there be issues with how I am saving the JSON file? Why does the autocomplete feature only work with the local array? Your insights are much appreciated.

Answer №1

Here are a few suggestions:

Many autocomplete libraries require that you bind to the input field only once. Based on your Stack Overflow post, it seems like you are binding on every keydown event, which means you are rebinding each time you type.

Instead, consider using this approach:

$(document).on('ready', function(){
  $("#university-field").autocomplete({
    source: universitydata
  });
});

This will bind the autocomplete only once, on page load.

Additionally, if you want to load JSON data from a file, you will need to make an AJAX request to retrieve and store it in a variable. Since the data is static and the dataset is relatively small, loading it as a variable before binding the autocompleter should work well. Place both the data and the autocomplete event binding in a separate .js file and include it with:

<script src="/your-path-to-the-javascript.js"></script>

Lastly, JavaScript naming conventions recommend using snake case for variables, so consider renaming your variable to universityData.

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

Obtain specific information from custom fields on the product page

What am I trying to achieve? I want to create a single product page that displays custom fields which need to be filled out before the item can be added to the cart. Additionally, I have implemented a button that should take all the values entered in the ...

Obtaining a worldwide JavaScript variable through AJAX JSON query

Hello, I have encountered an issue while using this code for my AJAX JSON request. When attempting to make jsonObj a global variable and then console.log() it, the debugger console shows that it is always coming up as undefined. To explain my question fur ...

Is it possible for a JWT generated using RS256 to be decoded on the jwt.io platform?

After setting up my first Express server and implementing user authentication with jwt, I'm now searching for a method to encrypt the jwt in order to prevent users from viewing the payload on the website. I am curious if anyone is aware of an encryp ...

When using the `array.join` method with nested arrays, it does not automatically include spaces in the output

function convertArrayToString(arr) { // Your solution goes here. let str = arr.join(", "); return str; } const nestedValues = [5, 6, [7], ["8", ["9", ["10" ]]]]; const convertedString = convertArrayToString(nestedValues); console.log(convertedString ...

Jasmine tests for AngularJS directive failed to invoke the link function

I can't figure out why the link function of my directive isn't being called in a Jasmine test. I've created a simple example to illustrate. Here is the code for my directive (TestDirective.js): 'use strict'; angular.module(&ap ...

How to seamlessly integrate Redux into your React project using create-react-app?

Is it correct to pass a reducer as props when using a rootreducer? This is the content of my rootReducer.js file: import { combineReducers } from 'redux'; import simpleReducer from './simpleReducer'; import messageReducer from '. ...

Tips for verifying if an object has been loaded prior to binding it with jQuery

When loading a "stub" file dynamically with jQuery that contains HTML objects, I aim to bind events to the loaded objects after they have finished loading. An example of what my external file may contain: <div id='myDiv'>click me</div& ...

Saving data inputted in a form using ReactJS and JavaScript for exporting later

What is the best way to save or export form input in a ReactJS/JS powered website? For example, if I have a form and want to save or export the data in a format like CSV after the user clicks Submit, what method should I use? Appreciate any advice. Thank ...

Retrieving a targeted data point from a JSON object

I am working with a json data that contains various properties, but I am only interested in extracting the uniqueIDs. Is there a way to retrieve ONLY the uniqueID values and have them returned to me as a comma separated list, for example: 11111, 22222? (I ...

Wrapping a group of elements with opening and closing tags using jQuery

I have a collection of distinct elements, like so: <section class="box-1"></section> <section class="box-2"></section> <section class="box-3"></section> My objective is to enclose all three elements within a div with a ...

Disabling Navigation with Arrow Keys in Prettyphoto

Is there a way to prevent arrow keys from functioning in PrettyPhoto for a specific instance? I have tried using keyboard_shortcuts:false, but it still reloads the frame if left or right arrow keys are pressed, causing the form inside to reset. However, co ...

Angular JS Form's Pristine feature is malfunctioning when attempting to reset

I implemented a login form on my website. After submitting the form, I clear it and set it to Pristine mode. However, the error message still persists. Below is the code for my form: <form name="loginForm" ng-submit="loginForm.$valid && login( ...

Encountering a 403 error while using the YouTube API

I have a setup where I display the latest uploaded YouTube videos on my channel. Everything seems to be working fine, but occasionally I encounter this error that causes my entire site to break! [phpBB Debug] PHP Warning: in file /my_youtube/functions.php ...

React-Redux Error: The function this.props.AppendCharacter is not defined

I have been looking for a solution to my issue but couldn't find anything that matches it. I am working on creating a calculator app using React & Redux, and whenever I click on one of the number buttons, I receive an error message saying "this.props. ...

React modal not triggered on click event

As a newcomer to react, I am exploring a modal component import React, { useState, useEffect } from 'react'; import { Modal, Button } from "react-bootstrap"; function TaskModal(props) { return ( <Modal show={pro ...

There was an issue retrieving the value from the $.ajax() error function, as it returned [

After successfully receiving data from the input field and sending it to the database, everything seems to be working fine. However, when attempting to retrieve the data after sending it to the database, an error is encountered: [object HTMLInputElement]. ...

Can Selenium successfully scrape data from this website?

I am currently attempting to extract Hate Symbol data (including the name, symbol type, description, ideology, location, and images) from the GPAHE website using Selenium. As one of my initial steps, I am trying to set the input_element to the XPATH of the ...

Optimizing CSS usage within Django: top recommendations

Throughout a 6-month-long project, I have continuously added new URLs. However, I am now encountering an issue when using the extend 'base.html' function on other pages where the CSS overlaps and creates confusion. My question is: What are the b ...

AJAX: Displaying the contents of a folder. Issue with URL resolution

I'm attempting to showcase a collection of images stored in a specific folder within a div. My approach involves utilizing AJAX within a JavaScript file titled edit, which is positioned one directory away from the index route. This implementation is b ...

Prop validation error: The property "title" must be a string with a value of **, but a number with a value of ** was provided

My Vue js code displays data from a JSON API in a modal. The issue is that the title should be dynamic, but it only works when clicked twice. On the first click, I get an error and the cancel button, which triggers the hidemodal() function, crashes. Can an ...