简体   繁体   中英

How do I get different id values from a form when making a DELETE request using AJAX in Rails?

I know I could be using "remote: true" for this but I really want to understand the inner workings of AJAX and how it works. This is the problem here, I am trying use a form input to send a DELETE request to the server but every time I submit the action I get a 404 message saying there's no routes that matches what I'm trying to do, I know the problem is that I am not getting the right id value from the form elements and that is reason why the error is being thrown. If someone could help me out on this one that'd be great. Here is my HTML code with the form tags:

<div class="pending-study-partners">

   <div id="257">
      <img alt="Default" class="avatar-image" src="/assets/default.png" style="width:70px;">

      <span class="friend-name"><a href="/users/4">Jamil Boykins</a></span>
      - <em>Friendship is pending</em> 

      <form accept-charset="UTF-8" action="/user_friendships/257" class="edit_user_friendship"     id="edit_user_friendship_257" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓"><input name="_method" type="hidden" value="delete"><input name="authenticity_token" type="hidden" value="lKp0BTPohxbRepgQmXhtwWXfxIMC8JvqpR1VnLSdz5s="></div>
        <input class="button radius tiny" name="commit" type="submit" value="Delete request">
</form> </div>  
    <div id="259">
      <img alt="Default" class="avatar-image" src="/assets/default.png" style="width:70px;">

    <span class="friend-name"><a href="/users/2">jamil shamill</a></span>
    - <em>Friendship is pending</em> 

    <form accept-charset="UTF-8" action="/user_friendships/259" class="edit_user_friendship" id="edit_user_friendship_259" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓"><input name="_method" type="hidden" value="delete"><input name="authenticity_token" type="hidden" value="lKp0BTPohxbRepgQmXhtwWXfxIMC8JvqpR1VnLSdz5s="></div>
        <input class="button radius tiny" name="commit" type="submit" value="Delete request">
</form> </div>  

Right now with my AJAX code I am able to delete the person and they disappear off the page only after I refresh the page, but when I click on the button to submit the form I get a 404 error. Here is my AJAX code:

  $(".edit_user_friendship").on("submit", function(event){
    event.preventDefault();
    var _this = $(this);
    var friend = _this.attr('id').split("_");

    $.ajax({
      url: "/user_friendships/"+friend[friend.length-1],
      method: "DELETE",
      dataType: "script",
      success: function(event, data){
        console.log(data);
        $tingzSon = $($(event.target).parent()[0]);
        $tingzSon.remove();
      }
    })
  })

If anyone could identify where I am going wrong that would be awesome.

Thanks a lot!

I get a 404 message saying there's no routes that matches, check your log where does the request is going. Obviously something is wrong with url: "/user_friendships/"+friend[friend.length-1]. If you add the log of the request and controller code that will be helpful.

If you're looking to use multi-delete, you'll have to pass the ids as an array of params:

#config/routes.rb
resources :items do 
    delete :multi_delete
end    

#app/views/controller/index.html.erb
<%= @items.each do |item| %>
   <%= content_for :div, id: item.id do %>
       <%= check_box_tag "delete", item.id %>
   <% end %>
<% end %>

<%= link_to "Delete", multi_delete_items_path, method: :delete, id: "multi_remove" %>

#app/assets/javascripts/application.js
$("#multi_remove").on("click", function() {
    $.ajax({
       url: $(this).attr("href"),
       data: $('input[name="delete"]').serialize();
    });
});

#app/controllers/items_controller.rb
def multi_delete
   ids = params[:delete]
   Item.destroy_all(ids) if defined?(ids)
end

I found out that the reason why that AJAX request wasn't working was because I was trying to send a DELETE request to the server and Rails actually requires you to do this by sending a POST request and passing in an additional data field in the AJAX request like this: data: {"_method":"delete"} in order for the server to actually delete that particular element that you are targeting. This is my revised code:

  $(".edit_user_friendship").on("submit", function(event){
    event.preventDefault();
    var _this = $(this);
    var friend = _this.attr('id').split("_");

    $.ajax({
      url: "/user_friendships/"+friend[friend.length-1],
      data: {"_method":"delete"},
      method: "POST",
      dataType: "json",
      success: function(data){
        console.log(data);
        _this.parent().remove();
      }
    });
  });

I hope others can learn from my mistake here, or shall I say lack of knowledge. I'm assuming Rails does this so older browsers that don't natively support more modern HTTP verbs like DELETE and PUT can still issue these requests without a hitch

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