-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.

1
  • 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 stackoverflow.com/questions/21032465/… Commented Nov 10, 2016 at 17:28

1 Answer 1

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!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.