0

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
rock
  • 348
  • 4
  • 18
  • Have you looked into [Rails remote form handling](https://guides.rubyonrails.org/working_with_javascript_in_rails.html)? That might help. You can set `remote=true` in your `form_for` (i think). It is curious because even without that, your code looks mostly right. I wonder about the redirect. If the `create` endpoint is truly ready for ajax, you could just return `head :ok` instead of the redirect. I wonder if the redirect is taking over? Are you seeing the console.log triggering when you submit? – mr rogers Sep 14 '20 at 02:05
  • @mrrogers added ``` remote: true```, still after one submission next submission is not working untill i reload page. – rock Sep 14 '20 at 02:12
  • console after one submission gives this error ```Error: Syntax error, unrecognized expression: input[name=project_director[status]``` – rock Sep 14 '20 at 02:17
  • Well - that's good data. The first hit correctly does *not* update the page, right? then the second one fails. I think with `remote=true` you probably don't need your on submit handler. Let me see if i can mock up an answer that might help. – mr rogers Sep 14 '20 at 02:21

1 Answers1

1

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

mr rogers
  • 3,200
  • 1
  • 19
  • 31
  • data is correctly passing now without page reload, but no sucess or error message is shown to user – rock Sep 14 '20 at 02:59
  • at this point the rails `flash` doesn't really work for you. it's counting on page reloads. So you'll have to handle that in the `ajax:success` listener. You can certainly update the response from the controller to hand back the success message like `render json: { success: "Way to go"}` then in the front end you'll need to put it on the page with javascript. – mr rogers Sep 14 '20 at 03:07
  • first time i am adding ajax so could you tell me how can i put on the page with javascript? – rock Sep 14 '20 at 03:12
  • I updated the solution and what your `ajax:success` event listenters might look like. – mr rogers Sep 14 '20 at 05:41
  • i have added turbo links but still alert response i only see on first submission not 2,3.. submission without page reload – rock Sep 14 '20 at 05:50
  • If you're using turbolinks, you need to change your document.onReady setup. Check out https://guides.rubyonrails.org/working_with_javascript_in_rails.html#turbolinks. The short story is that `$(function() { ... run when dom is ready ... })` which is what you have is insufficient. You'll need to an extra copy of that that is like `$(document).on('turbolinks:load', function() { ... run when dom is ready ... {))`. But I'd read the docs in that link or this SO post https://stackoverflow.com/questions/36110789/rails-5-how-to-use-document-ready-with-turbo-links. – mr rogers Sep 14 '20 at 05:57