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.