简体   繁体   中英

Understanding Ajax request with Rails

I currently have an Ajax request that I don't fully understand the behavior it's giving me. First, I'm not sure what the url is doing? Am I saying that is where it redirects after the call or that is the url of where it needs to be? I'll post the code and explain along the way.

AJAX

 $(document).on('click','.delete-snitch', function() {

    var snitchID = $(this).attr('data-snitch-id');
    $.ajax({
        type: 'DELETE',
        url: '/snitches/' + snitchID,
        success: function(){
            $('#tr-for-snitch-' + snitchID).fadeOut
        }
    });
});

See the url? When I use this as is I get a 404 error that the snitch was not found? I'm not sure why. but if I just have it render the snitch index page it still makes a page refresh which of course is not what I want. My question is -> What is the url doing in my case?

CONTROLLER

    def destroy
    DestroySnitch.perform(snitch: @snitch)

    respond_to do |format|
      format.html do
        redirect_to snitches_path, notice: "Snitch was successfully deleted."
      end
      format.js do
        binding.pry
      end
    end
  end

When I try to make the call and put a binding pry in the block for format.js it doesn't hit it? Any idea what I'm doing wrong here?

FORM

 <%= form_for @snitch, html: { class: "form-actions", method: 'delete' } do |form| %>
 <span class="button-text"><%= link_to 'NO WAY!', home_base_url_or_default(root_path), rel: "modal:close" %></span>
 <input type="submit" class="button button--modal delete-snitch" data-snitch-id="<%= @snitch.token %>" value="Yes, delete it.">
 <% end %>

The default action for that form is to send a 'post' request which results in a page refresh. Since you are handling the post request in your click function, you need to prevent the default action which is as simple as adding prevent_default to that function. You may want to change the function to listen for the form being submitted

 $(document).on('submit','.delete-snitch', function(event) {

   var snitchID = $(this).attr('data-snitch-id');
   $.ajax({
     type: 'DELETE',
     url: '/snitches/' + snitchID,
     success: function(){
       $('#tr-for-snitch-' + snitchID).fadeOut
     }
   });

   event.prevent_default();
 });

Rails has some helpers to work with AJAX which are worth reading.

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