2

I'm trying to create a simple form with two different submit buttons: one which will do a normal submit, and one which will do an ajax submit and render a partial. But I'm not sure how to do this because both go towards the same create action. I tried something like this:

/views/layouts/_form.html.erb:

<div id="theform">
<%= form_for(@user, :remote => true, :form_to_validate => 'user') do |f| %>

    Name: <div id='name'><%= f.text_field :name %></div><br/>
    Email: <div id='email'><%= f.text_field :email %></div><br/>
    Phone Number: <div id='phone_number'><%= f.text_field :phone_number%></div><br/>
    <%= f.submit "Normal Submit", name:'normal' %>
    <%= f.submit "Ajax Submit" %>

<% end %>
</div>

app/controllers/user_controller.rb:

class UsersController < ApplicationController

def new
    @user = User.new
end

def create
    @user = User.new(params[:user])
    if params[:normal]
        render :partial => "layouts/user"
    end
end

EDIT: this may seem like an odd task but it was an assignment given to me to demonstrate I could do it both ways. I know how to do the AJAX submit and the normal submit separately but my confusion is with having two submits in the form! :)

2
  • 2
    A step back: why would you show two buttons to do this? It seems like you'd only ever want to do one of these things: either a normal post, or via AJAX. i.e, you the programmer should know which is better for this situation and code it just to do one way. Furthermore, your "users" may not know what AJAX is so it seems odd to show them a button for it. Commented Jun 22, 2012 at 15:19
  • it was an example assignment given for me to do to demonstrate I can code both submits....I know how to do it one way or the other way I'm just unsure how to code the two different submits Commented Jun 22, 2012 at 15:34

2 Answers 2

1

Why not write some JS that listens to the click or submit and you route it in JS if its ajax $.ajax to the ajax location else let it go through normally if its not and dont stop the propagation.

Sign up to request clarification or add additional context in comments.

Comments

0

I don't think you need two submit buttons. Have the ajax button simply call the $.ajax method and send your data.

Alternately, you could have the ajax button call $('#formid').submit() after converting the form to be ajax, using whatever method you use to do so. This is probably the easier of the two methods.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.