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??
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%>
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] %>');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With