0

I'm running Rails and trying to set up an autocomplete on my text field. I want to submit to a controller method. If I'm submitting from my form (using the "Submit" button), I'd like to use the "format.html" branch. If I'm submitting using the autocomplete Ajax call, I'd like to use the "format.json" branch ...

  def search
    if params.has_key?("s")
      search = params[:s].strip
      @people = Person.where("name ilike ?", "%#{search.upcase}%")
      respond_to do |format|
        format.html {
          if @people.size == 1
            redirect_to controller: 'votes', action: 'show', id: @people.first.id
          end
        }
        format.json { @people.map(&:name) }
      end
    end
  end

I set up the autocomplete on my text field like so

$(function() {
  return $('#s').autocomplete({
    source: function(request, response) {
        $.get('/people/search', { s: request.term }, function(data) {
           alert(data)
           response(data.split('\n'));
        });
    }
  });
});

but what's happening is the value of "data" is an HTML page, as if I were submitting via the format.html method. How do I configure things so that my autocomplete call forces me to render the JSON response from my controller?

4
  • In your console, are you sure it's submitting as JSON? Seems it would be JS.
    – jvillian
    Commented Jan 29, 2018 at 22:31
  • I changed my "format.json" line to "format.js" but the "format.html" branch is still getting called.
    – user7055375
    Commented Jan 30, 2018 at 1:39
  • Can you add your console log? The bit that starts with Started GET... You may need to do: $.get('/people/search.js'....
    – jvillian
    Commented Jan 30, 2018 at 1:57
  • 1
    that worked after I made some other changes ... I had to add "protect_from_forgery except: :search" in my controller. I sense this could be bad but I'll open another question on that.
    – user7055375
    Commented Jan 30, 2018 at 2:48

1 Answer 1

1

Specify .json format in the url like this -

$.get('/people/search.json', { s: request.term }, function(data) {
   alert(data)
   response(data.split('\n'));
});

To send raw json data In Controller change. Otherwise it will look for template to build json (by default rails will look for search.json.jbuilder)

format.json { render json: {people: @people.pluck(:name)} }
1
  • When I did this the request resulted in an error, "PeopleController#search is missing a template for this request format and variant"
    – user7055375
    Commented Jan 30, 2018 at 1:32