I’m using the jQuery-UI Sortable Connected Lists. I’m saving the order of the connected lists to a Rails server.
My approach is to grab the list ID, column ID and index position of each list item. I want to then wrap this into an object that can be passed as a parameter back to the Rails Controller to be saved into the database. So ideally i’m looking to format the parameter like this: Parameters: {"Activity"=>[{id:1,column:2,position:1},{id:2,column:2,position:2} ,...]}
How do I properly format my parameters to be passed in this Ajax POST request?
Right now, with the approach below, I’m passing on Parameters: {"undefined"=>""}
This is my current jQuery code (Coffeescript) which doesn’t work:
jQuery ->
$('[id*="day"]').sortable(
connectWith: ".day"
placeholder: "ui-state-highlight"
update: (event, ui) ->
neworder = new Array()
$('[id*="day"] > li').each ->
column = $(this).attr("id")
index = ui.item.index() + 1
id = $("#" + column + " li:nth-child(" + index + ") ").attr('id')
passObject={}
passObject.id = id
passObject.column = column
passObject.index = index
neworder.push(passObject)
alert neworder
$.ajax
url: "sort"
type: "POST"
data: neworder
).disableSelection()
My apologies because this seems like a really amateur question but I’m just getting started with programming jQuery and Javascript.
Assuming that all your selectors are correct, then you should be able to do this:
You can also simplify the rest of your code:
Or even more compact (if you like that sort of thing):
Then you can
JSON.parse(params[:Activity])to unpack it in your controller.After a bit of discussion in the comments, I think your
indexvalues are wrong. Doing this:will give you the same
indexfor each<li>. You probably want something more like this:That should give you the index of the current
<li>(@) within the collection of<li>s that you’re iterating over. Alternatively, you could use the arguments thateachpasses to the iterator function: