I have a simple_form_for in my project. My goal is to alert people when their email is already in database thanks to an alert and ajax to reload the form if there is an error. When I send my form for the first time, I get the good respond from create.js.erb. But if I send the form a second time without reloading the page with the browser, my controller create method code is taken into account but not my create.js.erb code. For example, if I put an alert in the create.js.erb file, it doesn't pop the second time I send the form by clicking on the button again. Can you help me to figure why ?
pages_controller.rb
def create
@email = waiting_list_params[:email]
@waiting_user = WaitingList.new(waiting_list_params)
respond_to do |format|
if @waiting_user.save
UserMailer.welcome(@email).deliver_now
format.html { redirect_to concours_path }
format.js
else
format.html { render 'pages/concours' }
format.js { flash[:error] = @waiting_user.errors.full_messages[0] }
end
end
end
create.js.erb
function refreshForm(innerHTML) {
const newForm = document.getElementById("concours-form");
newForm.innerHTML = innerHTML;
}
<% if @waiting_user.errors.any? %>
refreshForm('<%= j render "pages/concours_form" %>');
confPopup.style.display = "none";
<% else %>
confPopup.style.display = "flex";
<% end %>
_form.html.erb
<%= simple_form_for @waiting_user, {id: 'concours-form', url: concours_path, remote: true} do |f| %>
<%= f.error_notification %>
<%= f.text_field :email,
class: "landing-form-input",
autocomplete: "off",
required: true,
pattern: '[^@]+@[^@]+\.[a-zA-Z]{2,6}',
placeholder: "Renseignez ton email ici"
%>
<i class="fa fa-envelope"></i>
<%= f.hidden_field :concours_city,
value:'',
id: 'c-choosen-city'
%>
<%= f.hidden_field :source,
value: params[:source]
%>
<%= f.button :submit,
class: "landing-form-button",
value: "Je tente ma chance !"
%>
<% end %>
routes.rb
get 'concours', to: 'pages#concours'
post 'concours', to: 'pages#create'