Search code examples
jqueryruby-on-railsajaxflash-message

Render flash message with Ajax call


I making an ajax call that deletes an object. Everything is working fine but now I need it display a flash message letting the user know that the object was deleted. I can't seem to find a simple way of doing this. Here is my code.

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.json do
        render json: [], status: :no_content
      end
    end
  end

AJAX

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

  $('.modal').modal('hide');

  $('.jquery-modal.blocker').hide();

  event.preventDefault();
});

Let me know if you need to see anything else? Thanks for the help.


Solution

  • If calling it through AJAX, probably requesting as JSON. If request comes over JSON, then It will not redirect it, but message will be sent.

    All you need is handle in AJAX callback, the message and redirection !

    def destroy
       DestroySnitch.perform(snitch: @snitch)
    
      respond_to do |format|
        format.html {redirect_to snitches_path, notice: "Snitch was successfully deleted."}
        format.json {render json: message: "DELETED COOL", status: :no_content} 
      end
    end