rock
rock

Reputation: 378

how to submit form data without page reload in rails application

project_director table has an attribute status,that has one_to_one association with project.
i am rendering projects with project_director form, on form submission every time my page reloads. i tried ajax from online resources but still my page reloads. here is what i tried.

index.html.erb

<%= form_for ProjectDirector.new do |f| %>
<td>
   <table class="approval-table">
      <tr>
         <td>
            <ul>
               <div>
                  <div class="wrapper-class">
                     <%= f.radio_button :status, true  %>
                     <%= f.label :approve %>
                     <br>
                     <%= f.radio_button :status, false  %>
                     <%= f.label :reject %>
                  </div>
                  <%=f.hidden_field :project_site_id, value: project_site.id%>
               </div>
            </ul>
         </td>
         <td>
            <%= f.hidden_field :user_id, value: current_user.id %>
            <%= f.submit 'Submit', :class => 'button primary small' %>
         </td>
      </tr>
   </table>
   <script>
      $(function(){
          $("#new_project_director").on("submit", function(event) {
              event.preventDefault();
      
              var formData = {
                  'status': $('input[name=project_director[status]]').val() //for get status
              };
              console.log(formData);
      
              $.ajax({
                  url: "/project_directors",
                  type: "post",
                  data: formData,
                  success: function(d) {
                      alert(d);
                  }
              });
          });
      })
      
   </script>
  </td>

project_directors_controller.rb

  def create
    @project_director =  ProjectDirector.new(remark_params)
      if @project_director.save
        redirect_to directors_index_path(anchor: 'panel2')
    end
  end
def remark_params
  params.require(:project_director).permit(:status, :projec_id, :user_id)
end

Upvotes: 0

Views: 1640

Answers (1)

mr rogers
mr rogers

Reputation: 3260

Rails gives you a lot of help here. I was able to get this working without a lot of extra javascript and without digging into the actual form fields because Rails already knows how that stuff is shaped and how it should work together.

Note: I have a model called Thing which has an accepted boolean attribute. This should correspond to your ProjectDirector (roughly).

in the form

<%= form_for(thing, remote: true) do |f| %>
  <%= f.check_box :accepted %>
  <%= f.submit 'Submit', :class => 'button primary small' %>
<% end %>

And in the controller

# things_controller.rb
  def create
    @thing = Thing.new(thing_params)


    if @thing.save
      if request.xhr?
        render json: { success: true }
      else
        redirect_to @thing, notice: "Thing was successfully created."
      end
    else
      render :new
    end
  end

If I create a new Thing the page does not refresh and it honors my boolean value.

You'll notice that there is no real additional javascript. Rails UJS handles this for me just by adding remote: true to the form.

This does not handle the possible redirect that you're trying to do which is to load up a new tab on the site. To trigger actions after a successful submit, you can add listeners for success and failure for that with something like

 $('#my-form-id').on('ajax:success', function(event){
    const [data, status, xhr] = event.detail
    alert(xhr.responseText)
    // or 
    alert(data.success)
 }).on('ajax:error',function(event){
    alert("Something went wrong")
 });

Check out this stackoverflow post or read Ruby on Rails guides here

Upvotes: 1

Related Questions