javascript - Ruby/JS how to reload page after submit button? -


i'm writing web app using ruby on rails. in controller:

  def create @category = category.new(category_params)  respond_to |format|   if @category.save     format.html { redirect_to @category, notice: 'category created.' }     format.json { render :show, status: :created, location: @category }     format.js { render js: 'window.top.location.href = "/categories";' }   else     format.html { render :new }     format.json { render json: @category.errors, status: :unprocessable_entity }   end  end 

in new.html.erb:

<h1>new category</h1> <%= render 'form' %> <%= link_to 'back', categories_path %> 

in _form.html.erb:

<%= form_for(@category) |f| %> <% if @category.errors.any? %> <div id="error_explanation">   <h2><%= pluralize(@category.errors.count, "error") %> prohibited category being saved:</h2>   <ul>   <% @category.errors.full_messages.each |message| %>     <li><%= message %></li>   <% end %>   </ul> </div> <% end %> <div class="field"> <%= f.label :content %><br> <%= f.text_field :content, placeholder: "content" %> </div> <div class="field"> <%= f.label :description %><br> <%= f.text_area :description, placeholder: "description" %> </div> <div class="actions"> <a href="#" onclick="window.top.location.reload(true)"><%= f.submit  %> </a> </div> <% end %> 

i want submit button function , newly created category saved before page refreshed. in code, page refreshed before saving. please help. thanks

i prefer using unobtrusive javascript. such, answer follows:

_form.html.erb

<%= form_for(@category, remote: true) |f| %>   ...   <div class="actions">     <%= f.submit %>   </a> </div> <% end %> 

categories_controller.rb

def create   @category = category.new(category_params)    respond_to |format|     if @category.save       format.html { redirect_to @category, notice: 'category created.' }       format.json { render :show, status: :created, location: @category }       format.js { render js: 'window.top.location.reload(true);' }     else       format.html { render :new }       format.json { render json: @category.errors, status: :unprocessable_entity }     end   end end 

note updated format.js render js script reload page, wanted. should know script work on page wherever js post request /categories called.


Comments

Popular posts from this blog

javascript - Laravel datatable invalid JSON response -

java - Exception in thread "main" org.springframework.context.ApplicationContextException: Unable to start embedded container; -

sql server 2008 - My Sql Code Get An Error Of Msg 245, Level 16, State 1, Line 1 Conversion failed when converting the varchar value '8:45 AM' to data type int -