Ajax:success without form action

Hello Stimulus users,

I try to use Sortablejs with stimulus + Rails backend.

image

this is my prototype.

when drag and drop end, I use ajax with Rails.ajax in stimulus controller.

    sortable = Sortable.create(this.collectionListTarget, {
      handle: ".drag-handle",
      animation: 150,
      swap: true,
      onEnd: (/**Event*/evt) => {
        var itemEl = evt.item;  // dragged HTMLElement
        console.log('on End')
        console.log(evt)
        console.log(ctrlThis.collectionListTarget)
        const data = 'collection[title]=UJS 테스트'
        Rails.ajax({
            url: "/collections",
            type: "post",
            contentType: 'html',
            data,
            success: function(data) {
              const event = [null, null, { response: data }]
              return true
            },
            error: function(data) {
              console.error('error => ', data)
            }
        })
      }
    })

create collection is for testing. ajax call is always succeed. but I don’t know where to set action for sort.

      <div data-controller="collections">
        <button data-action="click->collections#toggle" data-target="collections.toggler">
          create new collection
        </button>
        <%= form_with(
          model: Collection.new,
          data: { type: "html", target: "collections.form", action: "ajax:success->collections#onAddCollection ajax:error->collections#onAddCollectionError"},
          class: "d-none"
          ) do |form|
        %>
          <div>
            <%= form.text_field :title, data: { target: "collections.input" } %>
          </div>
           <input type="submit" value="Submit">
        <% end %>
        <ul id="collections" class="list-unstyled" data-target="collections.collectionList">
          <%= render @collections %>
        </ul>
      </div>

where is the right place for stimulus action? I don’t know where to set ajax:sucess handler.

    document.body.addEventListener('ajax:success', function(event) {
    })

this event listener only works when form action success.


I use custom action with Rails.fire, it works well. But I did not know it is best practice.

I’d love to know how this project is going. I’ve been searching for examples of using Sortable with Stimulus, and you seem to have the only post found so far. Mind sharing your implementation?

ChangJoo-Park,

I’m happy to try and help, but I’m actually having trouble following exactly what’s expected to happen when between the form and the onEnd function.

That said, I believe what you’re looking for to hear the ajax:success event dispatched by your Rails.ajax call in the onEnd function is this:

<div data-controller="collections" data-action="ajax:success@document->collections#onAddCollection">

Let me know if that helps!