I'm trying to set up an input tag with jquery autocomplete function, but it's doesn't work when Im referring to an external JSON data. It works perfectly, however, with local JSON-like array... Let me explain this in my code:
HTML file:
<html>
<head>
<meta charset="utf-8">
<script src="jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="jquery-ui-1.8.5.custom.min.js" type="text/javascript"></script>
<script>
$(function() {
$("#birds").autocomplete({
source: "http://localhost:3000/autocomplete_searches/index.json",
minLength: 3
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="birds">Birds: </label>
<input id="birds" />
</div>
</body>
</html>
autocomplete_searches_controller.rb in my Rails app
class AutocompleteSearchesController < ApplicationController
def index
@tags = Tag.limit(30).name_like(params[:term])
@tags_hash = []
@tags.each do |tag|
@tags_hash << {"label" => tag.label}
end
render :json => @tags_hash
end
end
This JSON action alone works very well, for example: http://localhost:3000/autocomplete_searches/index?term=psychiatric gives me:
[{"label":"Psychiatric Hospital"},{"label":"Psychiatric Nurse"},{"label":"Psychiatric Examination"}]
And I can see that my jQuery function is also working somehow, because when Im typing for example "italy" in my #birds input-box WEBrick gives me:
Started GET "/autocomplete_searches/index.json?term=italy" for 127.0.0.1 at 2010-09-27 18:07:07 +0200
Processing by AutocompleteSearchesController#index as JSON
Parameteres: {"term"=>"italy"}
bla bla bla SELECT "tags".* FROM "tags" WHERE (tags.name LIKE '%italy%') LIMIT 30
But I see no effects on the website. And as I said, autocomplete script is working perfectly when I put data in the same format straight in my html file. In this one Im not getting any problems:
<html>
<head>
<meta charset="utf-8">
<script src="jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="jquery-ui-1.8.5.custom.min.js" type="text/javascript"></script>
<script>
$(function() {
$("#birds").autocomplete({
source: [{"label":"Psychiatric Hospital"},{"label":"Psychiatric Nurse"},{"label":"Psychiatric Examination"}],
minLength: 3
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="birds">Birds: </label>
<input id="birds" />
</div>
</body>
</html>
So where's the problem? Im new to JSON so maybe Im doing sth wrong.