0

In this following block

$(document).on('turbolinks:load', function() {
  $('[data-js-usercontent-form]').on("ajax:success", function(event, data, status, xhr){
    var usercontent = $(xhr.responseText).hide();
    $('#usercontents').append(usercontent);
    usercontent.fadeIn(1000);
    document.getElementById('data-js-usercontent-form').reset();
  });

  $('[data-js-usercontent-id]').on("ajax:success", function(event, data, status, xhr){
    var usercontent_id = xhr.responseJSON.id;
    $('[data-js-usercontent-id=' + usercontent_id + ']').hide();
  });
});

One creates a usercontent and it will appear via the fadeIn.
One can delete a usercontent and it will be hidden. Well, in some cases.

The deletion works on a usercontent already created at time of page rendering, as the javascript has the usercontent_id to hide within the page code...
If a record is created and shown via AJAX, said record cannot be deleted until the page is refreshed.

Is there a solution to this situation (aside from page refresh)?

Daniel Batalla
  • 1,184
  • 1
  • 11
  • 22
Jerome
  • 5,583
  • 3
  • 33
  • 76

1 Answers1

1

I think that this is a classic event binding on dynamically created elements using jQuery.

You should binding the event in [data-js-usercontent-id]parent tag. For example, if a $('#usercontents') is the parent element of a [data-js-usercontent-id] tag, you script will be like this:

$('#usercontents').on('ajax:success', '[data-js-usercontent-id]',  function(event, data, status, xhr){
  var usercontent_id = xhr.responseJSON.id;
  $('[data-js-usercontent-id=' + usercontent_id + ']').hide();
});

You can check this response for a more detailed answer.

Daniel Batalla
  • 1,184
  • 1
  • 11
  • 22