简体   繁体   中英

Alerts without page reload Rails AJAX

I have a model Snippit and I want users to be able to delete a snippit, from a list, and then show an alert saying it was deleted, all using ajax. I have figured out how to do the actual deleting, but not the alert.

Here's the code:

snippits_controller.rb

  def destroy
    @snippit = Snippit.find(params[:id])
    @snippit.destroy
    respond_to do |format|
      format.html { redirect_to snippits_url}
      format.json { head :no_content }
      format.js {render :alert => "Sippit destroyed. "}
    end
  end

destroy.js.erb

$('#snippit_<%= @snippit.id %>').remove();

index.html.erb

<% @snippits.each do |snippit| %>
      <span class="panel panel-default" id="snippit_<%= snippit.id %>">
      <%= link_to edit_snippit_path(snippit), :class => "text" do %>
      <div class="panel-body">
        <h3 class="text"><%=snippit.title%></h3>
          <p class="trash"><%= link_to snippit, method: :delete, remote: true do %>
            <i class="fa fa-2x fa-trash-o"></i>
          <% end %></p>
          </div>
          <% end %>
          </span>
    <% end %>

Any and all help is greatly appreciated :)

If you want a JS alert response, then you'd want something like the following instead

format.js {render js: "alert('Sippit destroyed.');"}

The format.js render above means you're rendering a JS response. Your alert render :alert => "Sippit destroyed. " only works for HTML response because the flash[:alert] is rendered in the HTML page, but since you are rendering a JS response, then you'd either do the JS alert implementation above OR you partially update the HTML page to update the flash message by something like the following

destroy.js.erb

$('#snippit_<%= @snippit.id %>').remove();
$('#flash_container').html('<%= j render partial: "flash_container" %>');

UPDATE (Added working controller code for method 2: using destroy.js.erb above)

def destroy
  @snippit = Snippit.find(params[:id])
  @snippit.destroy
  respond_to do |format|
    format.html { redirect_to snippits_url}
    format.json { head :no_content }
    format.js { flash.now[:alert] = @snippit.destroyed? ? 'Sippit destroyed.' : @snippit.errors.full_messages }
  end
end

I added a failure-handler code above for format.js . It will set the flash alert message into either 'Sippit destroyed' if @snippit was successfully destroyed, OR into 'Some failure to destroy error' if @snippit was not destroyed.

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