Oranges13
Oranges13

Reputation: 1084

Rails Jquery Autocomplete with JSON fails

I am attempting to use a remote service to populate an autocomplete field that I have in rails. It is supposed to query and return available employees by last name

I have an action in my controller called employeeAutocomplete which gathers data from an outside database:

class ServicesController < ApplicationController
 def employeeAutocomplete
  @banner = employeeSearch(params[:term])
  respond_to do |format|
    format.json { render :json => @banner.to_json }
  end
 end

In my routes.rb I have a placeholder route:

match '/banner/cheese' => 'services#employeeAutocomplete'

I can successfully browse to http://0.0.0.0:3000/banner/cheese.json?term=mac and receive an array such as the following with employee data:

[ {"LAST_NAME": "MacDougal", "FIRST_NAME": "Elaine", "TITLE": "Internet Technician"}, {"LAST_NAME": "MacCallum", "FIRST_NAME": "Harvey", "TITLE": "Systems Architect"} ]

However, this does not work with the autocomplete field. Here's the javascript for my view:

$("#service_employeeLast").autocomplete({
    source: "/banner/cheese.json"
});

I receive an error in the firebug console: I receive an error in the firebug console

I'm at wits end. I do not know what I'm doing wrong, I've tried two different autocomplete plugins and keep getting this same error jquery.js:8103

Help!

Upvotes: 2

Views: 2245

Answers (2)

Oranges13
Oranges13

Reputation: 1084

Believe it or not it was Google Chrome causing the issue. Apparently it dislikes localhost ajax calls. Here is the updated code working as intended:

services.js

$(function() {
 $( "#service_employeeLast" ).autocomplete({
    source: "/banner/fetch",
    minLength: 2,

 });
});

services_controller

def employeeAutocomplete
    @banner = employeeSearch(params[:term])
    @banner_hash = []
    @banner.each do |b|
        @banner_hash << { 
            :title => b["POSITION_TITLE"], 
            :label => [b["FIRST_NAME"], b["LAST_NAME"]].join(" "), 
            :value => b["LAST_NAME"], 
        }
    end
    render :json => @banner_hash
end

The key here also that your return value hash has a label and value key/value pair

Upvotes: 2

Yanhao
Yanhao

Reputation: 5294

Maybe you encoded the data twice with render :json => @banner.to_json. It should be render :json => @banner, and the data will be encoded automatically.

Upvotes: 1

Related Questions