Mohammad Seif Mohammad Seif - 2 months ago 8
Ruby Question

How to Use Ajax in ruby on rails

I want send selected drop down menu value to controller by ajax

panel_controller.rb

class PanelController < ApplicationController

def insert
@city_ids = params[:city]
end
end


panel.js.erb

$(document).ready(function() {
$('#f_city_id').change(function() {
var city_js_id = this.value
$.ajax({
url: '/panel/insert',
type: 'GET',
data: {"city": city_js_id},
success: function (data,status)
{
alert(this.url);
}
});
return false;
});
});


routes.rb

get '/panel/insert' => 'panel#insert'


views/panel/insert.html.erb

<%= @city_ids %>



but @city_ids dont respond value after chenge drop down menu

Answer

You need to respond back from your insert method.

Try doing this

class PanelController < ApplicationController
  def insert
    @city_ids = params[:city]
    respond_to do |format|
      format.html { render partial: 'insert.html.erb' }
    end
  end
end

Create a partial file with the new content _insert.html.erb

<%= @city_ids %>

In you panel.js.erb try catching the response and append it in your DOM wherever necessary. Your updated value will be on the page.

$(document).ready(function() {
  $('#f_city_id').change(function() {
    var city_js_id = this.value
    $.ajax({
        url: '/panel/insert',
        type: 'GET',
        data: {"city": city_js_id},
        success: function (res){
            $("#somediv").html(res);
            //You will get the partial's content with the new data and you'll only need to append it to your page.
        }
    });
    return false;
  });
});