Sunday, 17 November 2024

Add Ajax Without partial

 Routes:   

get 'zzzz' => 'controllers#zzzz', :as => 'zzzz'

------

Controllers:
  include ActionView::Helpers::FormOptionsHelper
 skip_before_action :verify_authenticity_token, only: [:zzzz]
def zzzz
    bank_id = params[:bank_id]
    bank = Bank.find_by(id: bank_id)
    if bank.present?
      modes = options_for_auth_type(bank.mode)
    else
      modes = options_for_auth_type("E-mandate facility not available for this bank")
    end
    options = options_for_select(modes)
    render json: { options: modes }
  end

----------
html.erb file
<%=simple_form_for @customer, html: { class: 'form'} do |f|%>
<%= f.select :bank_id, options_for_select(select_bank, selected: f.object.bank_id), { include_blank: "Select Bank" }, { class: "chosen-select form-control mb-2 mr-sm-2", id: "bank_name", required: true } %>

<div class="col-sm-8">
                  <% if @customer.mode.present? %>
                    <%= f.select :auth_type, options_for_select(options_for_auth_type(@customer.mode), selected: f.object.auth_type), { include_blank: "Select Authorization" }, { class: "form-control mb-2 mr-sm-2"} %>
                  <% else %>
                    <%= f.select :auth_type, options_for_select([["Debit Card",'DebitCard'],["Net Banking",'NetBanking'],["Aadhaar", "Aadhaar"]], selected: f.object.auth_type), { include_blank: "Select Authorization" }, { class: "form-control mb-2 mr-sm-2"} %>
                  <% end %>
                </div>
<% end %>
<script type="text/javascript">
$(document).ready(function() {
  $('#bank_name').on('change', function() {
    var selectedBankId = $(this).val();  // Get selected bank ID
    $.ajax({
      url: '/zzzzz', // The URL where you send the request
      method: 'GET',
      data: { bank_id: selectedBankId },
      success: function(response) {
        var modes = response.options;
        var optionsHtml = '<option value="">Select Authorization</option>';
        $.each(modes, function(index, mode) {
          optionsHtml += '<option value="' + mode[1] + '">' + mode[0] + '</option>';
        });
        $('#customer_auth_type').html(optionsHtml);
      }
    });
  });
 });
</script>

No comments:

Post a Comment