Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to submit ajax/json requests with simple_form for Rails

With the standard Rails form_for, I was able to pass ajax requests though select and collection_select helpers as such:

<%= address.collection_select :country, @countries, :id, :name, {:include_blank => false}, "data-remote" => true, "data-url" => "/ajax/states", "data-type" => :json  %>

I can't seem to figure out how to do this with simple_form

like image 598
Nathan Avatar asked Apr 21 '12 00:04

Nathan


3 Answers

Figured it out. You just need to add the this:

:input_html => {"data-remote" => true, "data-url" => "/yoururl", "data-type" => :json}
like image 66
Nathan Avatar answered Oct 29 '22 22:10

Nathan


It is better to write it like this:

= simple_form_for sample_result, url: reject_sample_result_path(sample_result), method: :post, remote: true, input_html: {multipart: true} do |f|

When you explicitly declare data-url it will still first do the default route calculation, which in my case failed because the default routes did not exist (and should not exist --since I am overruling the url). When you declare just url it will just take the given url instead.

like image 9
nathanvda Avatar answered Oct 29 '22 23:10

nathanvda


I wanted to post a related follow up, because I had some difficulty figuring out how to implement the callback for this. I found this article to be very helpful: http://www.simonecarletti.com/blog/2010/06/unobtrusive-javascript-in-rails-3/

The secret is either to add an HTML5 data attribute, e.g. data-complete or (better) bind the ajax:complete or ajax:success callbacks provided by Rails to your form (see 4. Remote JavaScript Callbacks in article linked above):

From the article:

jQuery(function($) {
  // create a convenient toggleLoading function
  var toggleLoading = function() { $("#loading").toggle() };

  $("#tool-form")
    .bind("ajax:loading",  toggleLoading)
    .bind("ajax:complete", toggleLoading)
    .bind("ajax:success", function(event, data, status, xhr) {
      $("#response").html(data);
    });
});

CoffeeScript example:

$("#new_post").on("ajax:success", (e, data, status, xhr)->
  console.log data
)
like image 6
Dylan Avatar answered Oct 29 '22 23:10

Dylan