Cameron Aziz
Cameron Aziz

Reputation: 487

RoR - Convert submit form to AJAX from

I have a form that works well. Here is my partial:

<%= form_for @reservation, url: {controller: 'reservations', action: 'create'} do |f| %>
<div class="row">
  <div class="col-sm-8 col-sm-offset-1">
    <div class="form-group">
      <%= f.text_field :name, class: 'form-control', id: 'name', placeholder: 'Party Name', required: true %>
    </div>
    <div class="form-group">
      <div class="col-sm-4">
        Party Size:
      </div>
      <div class="col-sm-6">
        1 <%= f.radio_button :party_size, '1'%>&nbsp;&nbsp;&nbsp;
        2 <%= f.radio_button :party_size, '2'%>
      </div>
    </div>
    <div class="col-sm-4 col-sm-offset-8">
      <div class="form-group">
        <%= f.submit 'submit', class: 'btn default-btn btn-block' %>
      </div>
    </div>
  </div>
</div>

Here is the controller action create:

def create
  @reservation = Reservation.new(reservation_params)
  @reservation.customer_id = session[:customer_id]
  if @reservation.save
    redirect_to :back
  else
    render 'reservations/new'
  end
end

I would like to render 'reservations/confirmation' in place of the current partial reservations/form. I know I need to add remote: true, to the form_for tag, but I get stuck there. What & where do I need to write in JS to make this submit function work with AJAX? What do I need to add to the create action?

Upvotes: 0

Views: 30

Answers (1)

Chloe
Chloe

Reputation: 26294

You need to submit it via JQuery with $.post() and you also have to use respond_to to respond to both JavaScript submissions and normal HTML submissions (in case someone has JavaScript disabled).

http://guides.rubyonrails.org/working_with_javascript_in_rails.html#server-side-concerns

respond_to do |format|
  if @user.save
    format.html { redirect_to @user, notice: 'User was successfully created.'  } 
    format.js   {}
    format.json { render json: @user, status: :created, location: @user }
  else
    format.html { render action: "new" }
    format.json { render json: @user.errors, status: :unprocessable_entity }
  end
end

Upvotes: 1

Related Questions