John Sumner
John Sumner

Reputation: 95

Populating form with data using ajax response

I'm currently having a problem passing the values into the edit form using an ajax response, if I just respond by html and render the form it gets the email value passed in. But I'm having no luck trying to do this via ajax. Is there anything I'm doing glaringly wrong?

edit.js.erb

$('#edit-admin-modal').modal('show');
$('#admin_email').val('<%= @admin.email %>');
console.log('<%= @admin.email %>');

index.html.haml

  - @admins.each do |admin|
        %tr#admin[admin]
          %td= admin.email
          %td= admin.last_sign_in_at
          %td= admin.last_sign_in_ip
          %td.buttonColumn
            %button.adminShow.adminButton.btn.btn-primary{ type: 'button', disabled: 'disabled' } Show
          %td.buttonColumn
            = link_to 'Edit', "admins/#{admin.id}/edit", remote: true, class: 'btn btn-warning adminButton admin-edit'
          %td.buttonColumn
            = link_to 'Delete', "admins/#{admin.id}", method: :delete, remote: true, data: { confirm: 'Are you sure?' }, class: 'btn btn-danger adminButton'

_edit_form.html.haml

= form_for @admin, :url => {:action => "update", :id => @admin.id} do |f|
  .form-inputs.modal-body
    .form-group.row
      = f.label :email, 'Email',  class:('col-sm-2 col-form-label'), required: true
      .col-sm-10
        = f.email_field :email, class:('form-control')
        %div#emailUnique.confirmMessage
    .form-group.row
      = f.label :password, 'Password', class:('col-sm-2 col-form-label'), required: true
      .col-sm-10
        = f.password_field :password, class:('form-control')
    .form-group.row
      = f.label :confirm_Password, 'Confirm Password', class:('col-sm-2 col-form-label')
      .col-sm-10
        = f.password_field :password_confirmation, class:('form-control'), required: true
        %div#confirmMessage.confirmMessage
  .modal-footer
    = f.submit 'Update Admin', class:('btn btn-primary'), id:('admin-submit')

_edit_account_modal.html.haml

.modal#edit-admin-modal.fade{:role => "dialog", :tabindex => "-1"}
  .modal-dialog{:role => "document"}
    .modal-content
      .modal-header
        %button.close{"aria-label" => "Close", "data-dismiss" => "modal", :type => "button"}
          %span{"aria-hidden" => "true"} ×
        %h4.modal-title Update Account
        = render 'edit_form'

admins_controller.rb

def edit
    @admin = Admin.find(params[:id])
    respond_to do |format|
      format.html{redirect_to admins_url}
      format.js
    end
  end

Upvotes: 0

Views: 54

Answers (1)

fbelanger
fbelanger

Reputation: 3568

I would not bother editing each field individually. Instead maybe resend your form using ERB in your JS response.

$('#edit-admin-modal').modal('show');
$('.modal-content .some-form-wrapper').html('<%= j render "edit_form" %>')

This will behave like the HTML response in rails.

Make sure to rename the file to .js.erb.

Upvotes: 2

Related Questions