views:

78

answers:

2

Hello,

I am tying to use this code http://gist.github.com/110410 to dump Prototype in favor of jQuery but I do have a problem.

This is my HTML (a link_to generated link):

<a onclick="var f = document.createElement('form'); f.style.display = 'none'; this.parentNode.appendChild(f); f.method = 'POST'; f.action = this.href;var s = document.createElement('input'); s.setAttribute('type', 'hidden'); s.setAttribute('name', 'authenticity_token'); s.setAttribute('value', 'Mi6RcR6YDyvg2uNwGrpbeIJutSHa2fYboU37wSDE7AU='); f.appendChild(s);f.submit();return false;" class="post add_to_cart " href="/line_items?product_id=547">Add to cart</a>

Issue:

Everything works as it should except that the page does a reload. I suspect that the submit gets thru which causes a page reload.

Is there an elegant way to prevent that ? return false; doesn't seem to cut it in this case.

+1  A: 

Here is the answer to your question

tommasop
how is that answering my question ?
Cezar
A: 

ew. Use this (jQuery):

<a class="post add_to_cart" rel="Mi6RcR6YDyvg2uNwGrpbeIJutSHa2fYboU37wSDE7AU=" href="/line_items?product_id=547">Add to cart</a>
<script>
    $("a.add_to_cart").click(function(){
        $.post(this.href,{'authenticity_token':$(this).attr("rel")});
        return false;
    });
</script>

I put the authenticity token in the rel attr for the anchor assuming the token is unique to the product.


UPDATE

Because apparently Rails gives you no control of anything at all:

<a class="post add_to_cart" href="/line_items?product_id=547" onclick='            $.post(this.href,{"authenticity_token":"Mi6RcR6YDyvg2uNwGrpbeIJutSHa2fYboU37wSDE7AU="});return false;'>Add to cart</a>
David Murdoch
the entire onclick part is generated by a rails helper so I don't have to much control over that also, I wanna keep it for non javascript browsers. is there a way to intercept that submit without changing my html code ?
Cezar
I had no idea rails sucked so badly.
David Murdoch
You want to keep what for non-javascript browsers? the javascript? that doesn't make sense.
David Murdoch
the method you provided is still obtrusive, I don't wanna manually construct my link, I just wanna override the default link constructed by the rails helper. also if you disable javascript in your browser, that link won't pass the token.
Cezar
You do realize that what you are asking is not possible. An anchor element cannot perform a form POST (without javascript). Just put the auth token in the url.
David Murdoch