简体   繁体   中英

Sending data using ajax to the controller in rails

I am new to JS and rails so recently facing lots of difficulties about using ajax in rails environment. I will very appreciate if you contribute to developing my project. What I am trying to do is that Once a user selects data from the modal, I want to send the selected data to an action in the controller so that I can handle the data. I am not really sure where I can start with that. Please help guys :( Thanks a lot

view:

 <form id= "selected_form" action="" method="">
      <div id= "selected_form">
        <p id="checkids"></p>
      </div>
    </form>
    <!-- Modal -->
    <div class="modal fade" id="myModal" role="dialog">
      <div class="modal-dialog">
        <!-- Modal content-->
        <div class="modal-content">
          <div class="modal-header">
            <div>
              <button type="button" class="close" data-dismiss="modal">&times;</button>
              <h4 class="modal-title">Select Task</h4>
            </div>
            <div class="modal-body">
              <fieldset>
                <% @tasks.each do |task|%>
                  <div>
                    <label><input type="checkbox" value="<%=task.id%>" name="selected"><%=task.title%></label>
                  </div>
                <% end %>
              </fieldset>
            </div>
            <div class="modal-footer">
              <button type="button" id="save" class="btn btn-default" data-dismiss="modal">Save</button>
              <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
            </div>
          </div>
        </div>
      </div>
    </div>

JS

<script>
  $(function(){
    $(document).ready(function(){

    $("#save").click(function(){
      var checkedItem = [];
      $.each($("input[name='selected']:checked"), function(){
        checkedItem.push($(this).val());
      });
      $('#values').html("selected values are: " + checkedItem.join(", "));
      $.ajax({
        type: "POST", // request method for your action like get,post,put,delete
        url: "/users/<%= current_user.id %>/test", // route of your rails action
        data: {checked_items: checkedItem.join(", ")}, // attach data here you will get this data in your controller action with params[:checked_items]
        success: function(data, textStatus, jqXHR){}, // do whatever you want when it success
        error: function(jqXHR, textStatus, errorThrown){}
      })
    });

    });

  });
      </script>

Please check script below

<script>
  $(function(){
    $(document).ready(function(){

    $("#save").click(function(){
      var checkedItem = [];
      $.each($("input[name='selected']:checked"), function(){
        checkedItem.push($(this).val());
      });
      $('#values').html("selected values are: " + checkedItem.join(", "));
      $.ajax({
        type: "POST", // request method for your action like get,post,put,delete
        url: "/things", // route of your rails action
        data: {checked_items: checkedItem }, // attach data here you will get this data in your controller action with params[:checked_items]
        success: function(data, textStatus, jqXHR){...}, // do whatever you want when it success
        error: function(jqXHR, textStatus, errorThrown){...}
      })
    });

    });

  });

</script>

For simplicity you can inject rails path to that controller as dataset attribute. for eg

<form method="post" data-url="<%= tasks_path %>">

and in js part

  $('#save').on('click', function (e) {
    e.preventDefault();
    $.ajax({
      type: $(this).method || "GET",
      url: this.dataset.url,
      data: $(this).serialize(),
      success: function (response) {
        console.log(response)
      },
      error: function (error) {
        console.log(error);
      }
    });
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM