-1

I am trying to print a flash message after the user clicks a link, shown below in my js.erb file.

$('a').click(function(){
            <% flash.now[:alert]= "Successfully added  "%> this.innerHTML <% "to cart" %> 
        })

I want the flash message to say "Successfully added (whatever is clicked) to cart" I am having trouble because it seems like i have to embed javascript into the embedded ruby.

user6500179
  • 149
  • 1
  • 2
  • 12
  • I m assuming you are making Ajax call to add item to cart and after ajax success you want to show flash message? i guess you will find your answer here http://stackoverflow.com/questions/21032465/rails-doesnt-display-flash-messages-after-ajax-call – Satendra Nov 10 '16 at 17:28

1 Answers1

0

It seems like you have a misunderstanding of how ERB works. When you add ruby code to an ERB file, it's run on the server, and the output is inserted in it's place in the plain HTML which is sent to the client. So what your code is doing is running the ruby flash.new[:alert] = "Successfully added" and "to cart" on your server. And the Javascript function which is sent with the HTML to the client is:

$('a').click(function(){
    this.innerHTML
})

Which obviously doesn't do anything. What you probably want to do is send an AJAX request to the server from the javascript function with this.innerHTML and then run your ruby code upon receiving this request.

I'm sure this last paragraph seems like jargon to you, but hopefully this will give you some googling ammo. You have quite a few misunderstandings of how erb works and how flash works, and I can't really help you with those without a giant post which I can't really get into right now. Good luck googling!

thesecretmaster
  • 1,950
  • 1
  • 27
  • 39