1

I am developing an autocomplete form using JQuery and Rails. However I don't know how to pull values from my database to JQuery (I believe this has to be done via Rails).

This is my autocomplete function in jQuery

<script>
  $(document).ready(function() {
    $( "#BOOKSEARCH" ).autocomplete({
        source: programmingLang
    });
});
var programmingLang = ["ActionScript","AppleScript","Asp","BASIC","C","C++",
    "Clojure","COBOL","ColdFusion","Erlang","Fortran","Groovy","Haskell",
    "Java","JavaScript","Lisp","Perl","PHP","Python","Ruby","Scala","Scheme"];
</script>

However at the moment the autocomplete fills from a hard coded array. How can a fill this array with my data values from rails?

Thanks

3 Answers 3

2

Try this:

   var programmingLang = <%= Language.all.map(&:name).to_json.html_safe %>;

Assuming you have a model Language having name column

Make sure you dont have thousands or records, cause that will slow down or even may throw time out error.In that case you should use ajax. There are couple of answers which explain ajax thing.

or

 var programmingLang = <%= ruby_array.to_json.html_safe %>;
Sign up to request clarification or add additional context in comments.

Comments

0

You can do it with a simple AJAX request to an action that returns this array:

$(document).ready(function() {
  $.get('path-to-json', function(data){
    $( "#BOOKSEARCH" ).autocomplete({
      source: data
    });
});

2 Comments

If you have limited tags then there is no use of hitting server, Better bring records in form of an array..
That's true. It depends on how exactly the autocomplete is implemented. jQueryUI has some demos for dynamic (jqueryui.com/demos/autocomplete/#remote) and static (jqueryui.com/demos/autocomplete/#default) versions that might help.
0

your rails controllers need to return an array (or json object, depends on your js requirements) with these values.
you can call this controller via simple ajax call to retrive the data.
once you have the data you can populate it the same way.
you can find more info about rails ajax here.

1 Comment

If you have limited tags then there is no use of hitting server, Better bring records in form of an array..

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.