I recently revamped a form on my website to show or hide different field sets based on the selection of a select menu. I followed the guidelines outlined in the Symfony documentation.
As part of an effort to remove jQuery from my site and rely solely on vanilla JavaScript, I decided to convert the AJAX script responsible for sending form data after a select change to either XMLHttpRequest or the Fetch API. However, I encountered an issue where the Form's PreSubmit or PostSubmit events did not trigger as expected with these new methods.
Initially, I suspected that the request headers might be the culprit. Even after meticulously matching the headers in the Fetch API version to those in the Ajax request, the desired events still failed to fire. Only the PreSetData event was being triggered.
This is the original AJAX script:
let $ptoType = $("#pto_type");
$ptoType.off('change').on('change', function () {
let $form = $(this).closest('form');
let data = {};
data[$ptoType.attr('name')] = $ptoType.val();
$.ajax({
url: $form.attr('action'),
type: $form.attr('method'),
data: data,
success: function (html) {
$('#formStep2').replaceWith(
$(html).find('#formStep2')
);
}
});
});
This is the attempt using XMLHttpRequest:
// Code snippet for XMLHttpRequest would go here
And this is the attempt with the Fetch API:
// Code snippet for Fetch API implementation would go here
Despite checking the Network tab in the developer tools and debugging thoroughly, the issue persists where the pre-submit data event fails to trigger with both XMLHttpRequest and Fetch API implementations despite matching headers with the original Ajax version.