I’m trying to build a dynamic menu so when the user selects a country, the state menu is updated.
I’m looking at my dev logs and I see that the action runs the db query and then renders the json.erb file, but I can’t get any response from the browser.
Here’s what I have:
controllers/settings_controller.rb
respond_to :html, :json
def getstates
@states = Country.find_by_iso(params[:account][:addresses_attributes]["0"][:country]).states
respond_with(@states)
end
(Note: The form is a nested form, that’s why the params hash is so long.)
settings/edit.html.erb
<%= address.collection_select :country, Country.order(:name), :iso, :name, {:include_blank => true}, "data-remote" => true, "data-url" => "/settings/getstates", "data-type" => :json %>
<%= address.select :state, [], {:include_blank => true}, :disable => true %>
settings/getstates.json.erb
$(document).ready(function() {
$("#account_addresses_attributes_0_country").bind('ajax:success', function(evt, data, status, xhr){
var select = $('#account_addresses_attributes_0_state');
if (data !== null) {
select.removeAttr('disabled');
$.each(data, function(key, value) {
$("<option/>").val(value[1]).text(value[0]).appendTo(select);
});
} else {
select.empty();
select.attr('disabled', 'disabled');
}
});
});
(Note: I got this code from http://blog.madebydna.com/all/code/2011/12/05/ajax-in-rails-3.html)
Dev logs
Processing by SettingsController#getstates as JSON
Parameters: {"account"=>{"addresses_attributes"=>{"0"=>{"country"=>"UY"}}}}
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", "1"]]
Country Load (0.2ms) SELECT "countries".* FROM "countries" WHERE "countries"."iso" = 'UY' LIMIT 1
Rendered settings/getstates.json.erb (0.3ms)
Completed 200 OK in 3ms (Views: 1.5ms | ActiveRecord: 0.3ms)
This is the output I see in my dev logs. But nothing in the browser. I’ve tried adding alerts and console log methods, but nothing.
I’d really appreciate if someone could help me understand what I’m doing wrong.
If you use Firebug’s console tab, you’ll see the ajax request be made. Then you can open it up and see the response body. Like Ryan has suggested you’re requesting JSON but returning full javascript. So if you were to keep it that way you’d have to eval the response in your callback function i.e. eval(data) or jQuery also has a shortcut where you can request a ‘script’ type; But it’s kinda frowned upon now that RJS has been removed from Rails. Instead do as Dan has suggested, move the contents of settings/getstates.json.erb into your edit view, and delete the getstates.json.erb file. To aid you in making this work make the request/response simplier for now. Just do this and inspect it in Firebug to see what’s happening. After which, hook it up to turn the response contents into the option tags you’re wanting.