1

I'm trying to display an order summary on the final screen of a checkout process (buit in Rails 3). Nothing is submitted prior to this, so I'm using jQuery's serializeArray() to get all the names and values from the form fields, which works great. I collect a variety of nested attributes, so the returned array is rather busy, with names like order[donations_attributes][0][amount_in_dollars].

Is there a straightforward way, in Javascript (or using jQuery) to convert those names and values to a JSON string (which would make it way easier to work with to produce my summary output). For example, something like:

{
  "order": {
    "donations_attributes": [
      {
        "amount_in_dollars": 50.95,
        "category": "Some Fund"
      },
      {
        "amount_in_dollars": 90.92,
        "category": "Some Other Fund"
      }
    ],
    "billing_address_attributes": {
      "first_name": "Bob",
      "last_name": "Smith",
      "address1": "123 Whatever Street",
      "and so on": "etc"
    }
  }
}

Keep in mind that I haven't submitted anything yet (nor can I), so I can't do it in Ruby. Is there a sort of obvious, straightforward way to do this, or will I need to parse out and build the string by hand?

1 Answer 1

1

You can pass that data as-is to the data parameter in JQuery.ajax(...), and it will end up in parama in the controller method and view for the action you call, .e.g params[:order][:donations_attributes][0][:category] == "Some Fund".

If you want to load a new url into the browser, you can use JQuery.serialize() on the data and append it to your url (with a `"?" in between) to create the URL with the appropriate query string.

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

1 Comment

Thanks for the answer, but after reading up on jQuery.ajax(), it's not clear to me how this gets me the JSON string I'm looking for without a submit. (If it helps, I'm using mustache.js to generate the order summary. This all has to be done without making a request to the server.)

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.