0

I'm trying to get some jQuery Ajax working (new to me) and I managed to get it working, but only once. After the first time, it doesn't fire again until I refresh the page.

I found these answers, which I think might be relevant, also this, which uses the same "parent delegation" approach but still only applied to a single type of event (click OR change but not both). I'm not using "on click" or "on change" - I have .on to use both, and I'm not sure how to apply this fix to my .on?

This is my code:

$("#ajax-progress form").on("submit change", function(event) {
    event.preventDefault();
    var formValues = $(this).serialize();
    var sop_id = $(this).find('input[name=sop_id]').val();
    $.ajax({
        type: "POST",
        headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
        url: $(this).attr('action'),
        method: $(this).attr('method'),
        data: new FormData($(this)[0]),
        processData: false,
        contentType: false,
        success: function(response)
        {
            var $request = $.get('/ajax-progress?sop_id=' + sop_id);
            var $container = $('#ajax-progress');

            $container.addClass('loading'); // add loading class (optional)

            $request.done(function(includecontent) { // success
                $container.html(includecontent.html);
            });
            $request.always(function() {
                $container.removeClass('loading');
            });
        }
    });
});

I tried changing the start to:

$("#ajax-progress").on("submit change", "form", function(event) {

Which seems like it would be in line with the linked suggestions, but then my Ajax doesn't even fire once (no errors though in the element inspector console).

So instead of:

$(staticAncestors).on(eventName, dynamicChild, function() {});

I need something like:

$(staticAncestors).on(eventName, anotherEventName, dynamicChild, function() {});

Not sure if this is necessary information but the page contains a series of forms and when any of those forms changes or is submitted I want to be submitting the form data and reloading the entire list of forms (which does work once but then not again until refreshing the page).

Any guidance would be hugely appreciated.

Sam
  • 887
  • 1
  • 12
  • 27
  • 1
    I would guess that it's because you change the `#ajax-progress` html, in `$container.html(includecontent.html);` – Carsten Løvbo Andersen Sep 29 '22 at 08:29
  • Ah yeah to clarify, that is only reloading the form list. The HTML it loads is the same as what was there initially at page load (except now one or two classes have changed to visually reflect changes due to form submissions, but nothing affecting the jQuery selectors). – Sam Sep 29 '22 at 08:33
  • 1
    As @CarstenLøvboAndersen says, you're removing the original `form` element when you set the `html()` of its container, so the original event handler is lost. You need to use a delegated event handler instead - see the duplicate for how to do this. Also note that `bind()` is deprecated and shouldn't be used. Use `on()` instead. I'd also suggest you check what version of jQuery you're using. The latest version is 3.6.1 – Rory McCrossan Sep 29 '22 at 08:34
  • Yeah I'm 3.6.1. Do I just replace the "bind" with "on" and nothing else breaks, or is there more to it? – Sam Sep 29 '22 at 08:35
  • `$("#ajax-progress").on("submit change", 'form', function(event) {` – Rory McCrossan Sep 29 '22 at 08:36
  • Thanks, but this gives the same result as my `.bind` line at the end of the question (but appreciate this version at least isn't deprecated). So no errors, but no Ajax either (not even once) - form just submits in the classic, non-Ajax style. – Sam Sep 29 '22 at 08:40
  • So instead of `$(staticAncestors).on(eventName, dynamicChild, function() {});` I need something like `$(staticAncestors).on(eventName, anotherEventName, dynamicChild, function() {});` – Sam Sep 29 '22 at 08:42
  • Does this answer your question? [What is DOM Event delegation?](https://stackoverflow.com/questions/1687296/what-is-dom-event-delegation) – Nico Haase Oct 10 '22 at 07:28

0 Answers0