Kasra
Kasra

Reputation: 910

How to create an AJAX button?

I'm new to ROR programming and my question might seem newbie!

I have a Rails project. I need to save the subscribers data without refreshing the page!

In the last line of code block "app/views/users/new.html.haml" I need to change the form.button to An ajax button. I have included jQuery in the project. How should I code this? please consider that im beginner when you answer!

Thank you in advanced! (-_^)


This is routes:

users_new GET  /users/new(.:format)    users#new
users     GET  /users/index(.:format)  users#index
create    POST /users/create(.:format) users#create

This is my app/views/users/new.html.haml:

.form1
  %h1
    Subscriber
  =form_for @user, :url => :create do |form|
    - unless @user.errors.empty?
      - @user.errors.full_messages.each do |message|
        .alert.alert-danger
          %ul
            - @user.errors.full_messages.each do |message|
              %li= message
    %div
      .row.form-group
        .col-lg-3
          %label
            Email:
          =form.text_field :email, :class => 'form-control'
      .row.form-group
        .col-lg-3
          %label
            Name:
          =form.text_field :name, :class => 'form-control'
      .row.form-group
        .col-lg-3
          %label
            Phone Number:
          =form.text_field :phone_number, :class => 'form-control'
      .row.form-group
        .col-lg-3
          %label
            Address:
          =form.text_field :address, :class => 'form-control'
      %div=form.button 'Save', :class => 'btn btn-primary'

This is app/controllers/users_controller.rb:

 class UsersController < ApplicationController

   def index
   end

   def new
     @user = User.new
   end

   def create
     @user = User.new params[:user]
     @user.save
     redirect_to users_new_path
   end

 end

Upvotes: 0

Views: 131

Answers (1)

Jakub K
Jakub K

Reputation: 1711

To make the form into an ajax form really all you need to do is set remote option to true, this will automatically send the form using ajax:

=form_for @user, :url => :create, :remote => true do |form|

You will also need to create some response to it. Here is a great railscast on the topic: http://railscasts.com/episodes/136-jquery-ajax-revised

Upvotes: 1

Related Questions