5

I've tried different variants of make flash[:notice] working without reload.

Stackoverflow gave me this - How do you handle Rail's flash with Ajax requests?, but I can't find solution, that worked for me.

For example, added to my controller:

def create
  @entry = Entry.new(params[:entry])
  respond_to do |format|
  if @entry.save
    format.html { redirect_to @entry, notice: 'Entry was successfully created.' }
    format.js {
  flash.now[:notice] = 'Website was successfully created.'
 render action: 'create'
}
  else
    format.html { render action: "new" }
    format.js { render action: "new" }
  end
  end
end

create.js

   $('<%= j render @website %>').appendTo('#websites').hide().fadeIn();
  $(".alert").html("<%= escape_javascript(flash[:notice]) %>"); $(".alert").show(300);
  $("#new_website")[0].reset();

but it didn't work.

Can someone tell me understandable full solution, that worked for him ?

Community
  • 1
  • 1
Denys Medynskyi
  • 2,353
  • 8
  • 39
  • 70

2 Answers2

2

Do you make a typo on your js template filename? it should be create.js.erb but not create.js
and please strictly follow the https://stackoverflow.com/a/8873592/557863 , then make your changes on it.

Community
  • 1
  • 1
raykin
  • 1,757
  • 1
  • 14
  • 19
0

You're submitting new entries via Ajax, so you shouldn't use the flash -- it's intended for redirect responses, but you're not redirecting. To indicate success or failure, you'd need to write that into your JavaScript response.

Tuesdave
  • 669
  • 2
  • 8
  • 26