Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Ajax To Update a Partial in Rails

I'm a beginner programmer in Rails and I'm currently trying to create a simple form which takes a name, email, and phone number, and then when you click submit updates the page with what you have entered using Ajax.

i.e. if you enter User, [email protected], and 555-555-555 into the text fields of the form and click submit, you should get

Name: User Email: [email protected] Phone Number: 555-555-555

I know this is a simple question but I'm not quite sure how to write the JavaScript to make it work.

Here's my code for the partial:

<%= form_for(@user, :remote => true) do |f| %>

Name: <div="Name"><%= f.text_field :name %></div>
Email: <div="Email"><%= f.text_field :email %></div><br/>
Phone Number: <div="Phone Number"><%= f.text_field :phone_number%></div><br/>
<%= f.submit "Submit" %>

My controller looks like this:

class UsersController < ApplicationController

def new
    @user = User.new
end

def create
    @user = User.new(params[:user])
end
end

In my create.js.erb file do I use the .update function to replace the text fields with the entered information or do I do something else??

like image 754
tkrishnan Avatar asked Jun 21 '12 18:06

tkrishnan


2 Answers

If you wrap your form in a div, you can replace its contents easily later:

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

Name: <div="Name"><%= f.text_field :name %></div>
Email: <div="Email"><%= f.text_field :email %></div><br/>
Phone Number: <div="Phone Number"><%= f.text_field :phone_number%></div><br/>
<%= f.submit "Submit" %>
</div>

Then in your create.js.erb file:

$("#theform").html("<%= escape_javascript(render partial: "users/user", locals: {user: @user}) %>");

And in your /app/views/users/_user.html.erb

Name: <%= user.name%> Email: <%= user.email%> Phone Number: <%= user.phone%>
like image 82
Jesse Wolgamott Avatar answered Sep 20 '22 17:09

Jesse Wolgamott


you got to you remote true on your form and make your controller respond to a js

View:

<%= form_for(@user, :remote => true) do |f| %>
  Name: <div="Name"><%= f.text_field :name %></div>
  Email: <div="Email"><%= f.text_field :email %></div><br/>
  Phone Number: <div="Phone Number"><%= f.text_field :phone_number%></div><br/>
<%= f.submit "Submit" %>

Controller:

class UsersController < ApplicationController

  def create
    @user = User.new(params[:user])
    @user.save
    respond_to do |format|
      flash[:notice] = "saved successful"
      format.js # new.js.erb 
    end
  end
end

and create a new file named new.js.erb with the ajax code and use ruby embedded sintax as you please

$('div#my_id').html('<%= @user.name%> - <%= @user.phone %>');
$('div#notice').html('<%= flash[:notice] %>');
like image 26
Pedro Medeiros Avatar answered Sep 17 '22 17:09

Pedro Medeiros