Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails pass params through ajax request using JSON

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

like image 428
Laurence Avatar asked Jan 02 '23 06:01

Laurence


1 Answers

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.

like image 92
Laurence Avatar answered Jan 05 '23 16:01

Laurence