Reputation: 353
I am new to rails and I am trying to configure my form to submit a request via ajax. My page has a popup using bootstrap that has the form.
If the data is valid, then I would like the page to redirect to the original page ('new' action). If there is a duplicate member (model returned false on save), then I want to display this error message:
"You already exist in our system or your e-mail address is a duplicate. Please sign in if you have registered before."
Here is the view (only some):
<%= form_for(@person, url: {controller: "sign_ins"},html: {class: "form-signup",
id: "signupform"}, remote: true) do |f| %>
<p id="info_text" class="lead">Please enter the information below to register.</p>
<div id = "err_msg"></div>
<%= render("shared/companylist") %>
<%= f.text_field :first_name, class: "form-control fieldBottomMargin", placeholder: "First Name", required: true %>
<%= f.text_field :last_name, class: "form-control fieldBottomMargin", placeholder: "Last Name", required: true %>
<%= f.phone_field :phone, class: "form-control fieldBottomMargin",
placeholder: "Phone Number (No Dashes)", required: true, pattern: "([0-9]{10})" %>
<%= f.email_field :email, class: "form-control fieldBottomMargin", placeholder: "E-mail", required: true%>
<%= f.button "Register", class: "btn btn-lg btn-primary btn-block", id: "btnsubmit" %>
<% end %>
This is my controller create action, which I don't know if it is correct:
def create
@person = Person.new(person_params) #Call 'strong paremeters' method.
respond_to do |format|
if @person.save
format.html {redirect_to home_url}
format.js {}
else
@err_msg = "You already exist in our system or your e-mail address is a duplicate.
Please sign in if you have registered before."
format.js {}
end
end
end
and here is my (failed) js file, which I can't find out how to configure.
$('#err_msg').html('<div class="alert alert-danger"><%= j @err_message %></div>');
have been working on this for hours. appreciate any help. thank you.
Upvotes: 2
Views: 1495
Reputation: 3587
In your create.js.erb file, you can use jquery to display that.
$('#err_msg').html('<div class="alert alert-danger"><%= j @err_message %></div>');
To redirect if the object is saved, do the following in your controller:
format.js { render js: 'window.location.href = "/your_desired_path";' }
These should be enough!
Upvotes: 2