Search code examples
jqueryruby-on-railsruby-on-rails-3ujs

Making use of jquery-rails (ujs) when creating manual ajax requests


I implemented jQuery's draggable/droppable for a list of notes to order them hierarchically, which works fine at the moment, but I feel like I am doing too much.

The whole csrf part is sent manually with the request and I am also manually evaluating the response, which are features that ujs provides. Is there a way to integrate this seamlessly so that I can use the advantages of the ujs lib?

A possible solution I thought of would be to wrap the whole draggable into a <form data-remote="true"> but that feels a bit hackish.

$(function()
{   
    $('#notes-container .note').draggable();

    $('#notes-container .note').droppable({
        drop: function(event, ui)
        {
            $.ajax({
                type: 'PUT',
                url: ui.draggable.find('form').attr('action'),
                data: { 
                    authenticity_token: $('meta[name="csrf-token"]').attr('content'),

                    task: { 
                        parent_id: $(this).data('id') 
                    } 
                }
            });
        }
    });

});

Solution

  • Solved by adding the whole form that I need into the element, and then making the draggable/droppable callbacks fill in the values the form needs and firing the .submit() which then is handled by jquery-rails.