How To Submit A JavaScript Array Via XHR?

Hello,

I would like to create a button that, when clicked, pulls a subset of
fields out a form on the same page and sends those fields’ values as
an array to the server as an XHR.

The server’s response would then be used to update another element on
the page.

So far I have got a button that pulls the subset of fields from the
form and bundles their values into an array. But I don’t know how to
submit this via XHR to the server.

My code looks like this:

<%= button_to_function ‘Calculate price’, ‘bundle_order();’ %>

where bundle_order() is a JavaScript function I wrote in application.js.

Can anyone help?

Thanks and regards,
Andy S.

On 30 Mar 2007, at 12:23, Andrew S. wrote:

I would like to create a button that, when clicked, pulls a subset
of fields out a form on the same page and sends those fields’
values as an array to the server as an XHR.

The server’s response would then be used to update another element
on the page.

So far I have got a button that pulls the subset of fields from the
form and bundles their values into an array. But I don’t know how
to submit this via XHR to the server.

I just worked out how to do this. Here it is lest anyone else is
interested:

  1. Make a JavaScript function that returns a hash of the elements
    you wish to submit (not an array as I originally did). For example:

public/javascripts/application.js:

 function subset() {
   p1 = $F('dom-id-of-element-x')
   p2 = $F('dom-id-of-element-y')
   return $H({ x: p1, y: p2 });
 }
  1. Use the link_to_remote helper and – here’s the part I was
    missing before – pass the :with key:

app/views/your_controller/your_action.rhtml:

 <%= link_to_remote 'Do something...',
                    :url    => {:action => 'foo'},
                    :update => 'dom-id-to-update',
                    :with   => 'subset()' %>

Hope that helps somebody.

Regards,
Andy S.