Gray Kemmey
Gray Kemmey

Reputation: 1002

What's the rails way to post form data to a third party web service?

I have a simple form with one text area that submits the string in the text area as JSON to an external web service. Here's what it looks like before the form is submitted:

before

And here's what it looks like after the form is submitted:

after

And here's the html.erb code that created the form:

<script type="text/javascript">
  function call_service() {
    var data_to_send = document.getElementById("data_to_send").value;

    $.ajax({
      url : "http://externalservice.com",
      data : data_to_send,
      type : "POST",
      dataType : "json",
      contentType: "application/json"
    }).done(function(data) {
      // populate the table
    }).error(function(data) {
      // handle error
    });
  }

  $(document).ready(function() {
    $("#table_div").hide();
  });
</script>

<!-- heading html redacted -->

<!-- <%= form_tag("http://externalservice.com", 
                      method: :post,
                      remote: true,
                      role: "form",
                      data: "json") do %> -->

<form role="form">
  <h4 class="form-heading">Enter Data:</h4>
    <%= text_area_tag("data_to_send", @data, 
                          rows: 5, 
                          class: "form-control",
                          style: "font-family: Monaco;") %>
    <p class="help-block">
      Here you can edit the JSON data or click "Generate" to just
      use the data that's already there.
    </p>
    <%= button_to_function("Generate Table!", "call_service(); this.blur()" ,class: "btn btn-primary") %>
<!-- <% end %> -->
</form>

<!-- table html redacted -->

Where the commented out form_tag is what I was trying to do before I just decided to make things work using jQuery and the button_to_function bit.

My question is how do I accomplish the same thing--a form that sends JSON data to an external service--the rails way? Whether that's with a remote: true form or otherwise?

Upvotes: 0

Views: 686

Answers (1)

Litmus
Litmus

Reputation: 10996

If the 3rd party webservice is REST compliant, you may want to give ActiveResource a try.

Also read this Q/A for some more hints.

Upvotes: 1

Related Questions