bcackerman
bcackerman

Reputation: 1554

Rails 3.1 Submit form without refresh

I've got a form here on my orders/_form.html.erb that I want to submit and save in a table called Categories

<%= simple_form_for(@category) do |f| %>

  <%= f.error_notification %>

  <div class="inputs">

    <%= f.input :name, 

:label => false, 

:input_html => { :class => 'text', 

:style => 'float:left; width:250px' }, 

:placeholder => "Type of item / name of expense",


%>



   <%= f.hidden_field :user_id, 

:value => current_user.id %>


   <%= f.button :submit, 

:value => 'Add Category', 

:class => 'small grey',

:style => 'margin:5px 0 0 10px' %>


  </div>



<% end %>

In my categories_controller.rb I have this code to create the category:

# POST /categories

  # POST /categories.json

  def create

    @category = current_user.categories.build(params[:category])



    respond_to do |format|

      if @category.save

        format.html { redirect_to new_order_path }

        format.json { render json: new_order_path, status: :created, location: @category }

      else

        format.html { render action: "new" }

        format.json { render json: @category.errors, status: :unprocessable_entity }

      end

    end

  end

First, how do I make it so that when you submit the form, it doesn't refresh the page? Then I want the Categories dropdown http://d.pr/gUwz to have the new entry in there as well (I assume using JQ). Any idea how to get me started with this?

Upvotes: 2

Views: 2330

Answers (3)

sameera207
sameera207

Reputation: 16619

With Rails 3.x you have to use :remote => true with form

Ex:

<%= form_for @comment, :remote => true, :html => { :'data-type' => 'html', :id => 
 <form code>
<% end %>

and make sure you include jQuery js files.

Upvotes: 2

You shold send a ajax request in the form tag using:

:remote => true

Check the docs about for_for method: FormHelper#form_for-instance_method

Since JQuery is default to rails 3.0 you should have no problems doing that.

Upvotes: 1

Arvind singh
Arvind singh

Reputation: 1392

Need to use :remote => true in form tag, this will submit form as with ajax request and form will get submitted without refreshing page.

Upvotes: 0

Related Questions