views:

665

answers:

2

I am used to use the helper methods link_to_remote and friends to create links or buttons that will send Ajax request under the hood and update some data of the webpage.

I have some which background images are buttons. I want them to send Ajax request to my rails server. I guess a javascript onClick + sending Ajax request should do the magic but I have no idea of how Prototype works under the Rails helper method.

I hope this is not a too lame question

+2  A: 
$("my_button").observe('click', function(){
    new Ajax.Request(url, {
                             method: 'get',
                             parameters: { "key": "value" },
                             onSuccess: function(res){
                                // handle the result
                             }
                         });
}

and that's it.

pilif
+2  A: 

The method on the element is observe Also, $() assumes you are using an id. If you have a set of buttons tagged with classes, rather than ids, you could use $$() which takes a css selector and returns an array of elements.

You could take the result from that and iterate over it, adding click behavior to each button.

$$(".bg_button").each(function(button){
    button.observe('click', function(){
        new Ajax.Request(url, {
                                 method: 'get',
                                 parameters: { key: 'value' },
                                 onSuccess: function(res){
                                    // handle the result
                                 }
                             });
    });
});

To learn more about how prototype works, look at their api docs. I think they are pretty good.

BaroqueBobcat
I was just browsing the docs right now, it took time to know where to look at but now I have it clear. Thanks a lot
Jordi