3

Currently I am using ajax to submit my sortable items, but I would like to do a non-ajax submit. Is that possible?

Current ajax post:

$("#create_items_form").submit(function() {
    $.ajax({
      type: "POST",
      url: $(this).attr("action"),
      dataType: "script",
      data:  $("#destination_items").sortable('serialize')
    });
    return false;
});

html:

<%= form_for(@items, :url => create_items_path, :html => {:id => "create_items_form"}) do |f| %>
    <ul id="destination_items"></ul>
<%= f.submit "Save", :id => "create_items_button" %>

Because of that I get a nice array to use in my controller:

Params: "items"=>["8", "10"]

Is it possible make this information available via a normal submit?

Thanks!

mu is too short
  • 426,620
  • 70
  • 833
  • 800
EverTheLearner
  • 7,040
  • 16
  • 57
  • 72

2 Answers2

6

You could fill a hidden input with the serialized data on submit. In this you don't need to return false in your event handler, because you don't want to stop the submit event.

Add to your form:

<input id="someid" name="yourfieldname" type="hidden">

Bind a on submit event:

$("#create_items_form").on('submit', function() {
    $('someid').val($("#destination_items").sortable('serialize'));
}); 
Fox32
  • 13,126
  • 9
  • 50
  • 71
  • I tried this but its passing a string instead of an array object. Is it possible to pass an array in an html hidden input tag? – EverTheLearner Feb 27 '12 at 20:22
  • 1
    @EverTheLearner: you can parse that string into a hash using this: http://stackoverflow.com/questions/2772778/parse-string-as-if-it-were-a-querystring-in-ruby-on-rails – DCoder Feb 27 '12 at 20:48
  • @DCoder: Thanks! That helped with parsing the string! – EverTheLearner Feb 28 '12 at 01:56
  • 1
    This is a side note, but you should not be using the submit event to place the data in the hidden field, rather use jquery's sortable to detect a change to the sort order and populate the hidden field on change. That way you do not risk the from submit occurring before the hidden field gets data. – Fresheyeball Mar 05 '12 at 18:48
0

I believe that a previous post has answered your issue, but now that you are dwelling into serializing arrays etc, the below plugins will help.

http://www.onegeek.com.au/projects/javascript-serialization

http://amplifyjs.com/

bPratik
  • 6,894
  • 4
  • 36
  • 67