Reputation: 377
I'm using rails 5.2 and I would like to have a country and city selection form. I'm using the city-state gem to have dropdowns containing all the countries and cities, however, the cities dropdown needs to know the country selected beforehand.
I thought this would be best done using ajax to pass the selected country using an input eventlistener on its dropdown.
My problem is that the ajax request doesn't pass the JSON variable that I'm writing but it passes {"object Object"=>nil, "id"=>"1"}.
This is what I have for now:
<%= form_with(model: @user) do |form| %>
<%= form.select :country, CS.countries.values.sort, { :prompt => 'Country'} %>
<%= form.select :city, CS.states('placeholder').keys.flat_map { |state| CS.cities(state, 'placeholder') }, { :prompt => 'City'} %>
<%= form.submit %>
<% end %>
<script>
var countryForm = document.getElementById('user_country');
countryForm.addEventListener('input', function (evt) {
var country = this.value;
Rails.ajax({
type: "GET",
url: '/users/' + <%= params[:id] %> + '/country',
dataType:'json',
data : {'country': country},
error: function (xhr, status, error) {
console.log('error')
console.error('AJAX Error: ' + status + error);
},
success: function (response) {
}
});
});
</script>
This is what I see in console after the request:
Started GET "/users/1/country?[object%20Object]" for 127.0.0.1 at 2018-06-13 13:19:50 +0200
Processing by UsersController#country as JSON
Parameters: {"object Object"=>nil, "id"=>"1"}
Completed 204 No Content in 1ms (ActiveRecord: 0.0ms)
Any idea what I'm doing wrong? I've tried looking everywhere but I don't see any rails 5 guides on how to use JSON in Ajax. Please help. Thanks
Upvotes: 4
Views: 6834
Reputation: 239087
I ran into a similar issue. Then I learned about the URLSearchParams interface, which is supported by all modern browsers.
Rails.ajax({
type: 'GET',
url: '/users/' + <%= params[:id] %> + '/country',
data: new URLSearchParams({'country': country}).toString(),
success: function (response) {
// ...
}
})
Upvotes: 4
Reputation: 377
Found the solution on this link after searching everywhere: https://learnetto.com/blog/how-to-make-ajax-calls-in-rails-5-1-with-or-without-jquery
The code for the request can be written like this:
Rails.ajax({
type: "POST",
url: "/things",
data: mydata,
success: function(repsonse){...},
error: function(repsonse){...}
})
Except for one thing! As far as I can tell, you can’t simply send JSON data. So we need to convert mydata to application/x-www-form-urlencoded content type manually like this:
mydata = 'thing[field1]=value1&thing[field2]=value2'
When doing this I obtain the params in the correct way:
Parameters: {"thing"=>{"field1"=>"value1", "field2"=>"value2"}, "id"=>"1"}
Apparently there is an automatic conversion of the data object which happened in the jquery days but is missing with the rails-ujs version.
Upvotes: 7
Reputation: 12203
Use JSON.stringify()
on your data:
data: JSON.stringify({'country': country}),
You're currently passing an Object through the call rather than JSON, which is causing the issue. I'm pretty sure this will fix things for you.
Your id
param is fine as it's passed through the URL, though the data itself needs to be passed as a JSON string.
Upvotes: 2