0

Please note, this is for a rails app. I've been working through trying to find the best way to pull data from a json file, and I can't quite seem to find the answer with what I want to do anywhere. I have a list of static data, like so (It's a list like 8,000 lines long):

    [
    {"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 saved the above in my apps/assets/javascripts folder as universitydata.json

And my javascript:

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

Here's the embedded ruby file where I have the event for the updateUniSearch() function as being on keydown:

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

So, let's say i define universitydata as the following:

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

And then I go to type in the autocomplete form 'm'- 'Maine" will appear as an option. But in this file I have saved as universitydata.json in my javascript assets folder, nothing happens. Am I setting this up all wrong? Am I saving this json file improperly? Why does it only work with the local array? Thank you in advance.

1 Answer 1

1

A few things:

Most autocomplete libs require that you only “bind” to the input once. Based on your stack overflow post, you have it happening in the onkeydown event. So every time you type, you're rebinding to the input.

Consider instead:

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

This will bind the autocomplete only once (on page load)

Secondly, and to answer your primary question, if you wanted to load the json data from file, you'd have to issue an AJAX request to load it into a variable. Given the data is static and the dataset is realatively small, it's perfectly fine to have it loaded as a variable before you bind the autocompleter. Put all of this (the data and your autocomplete event binding) in a .js file and use

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

Thirdly, JavaScipt conventions recommend snake case for variable names, so consider naming your variable universityData

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.