Symfony form events failing to trigger after converting AJAX request to vanilla Javascript

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.

Answer №1

After reviewing the documentation link you provided, it seems like you are using Symfony 6.1.

To resolve your issue quickly and without any JavaScript configuration, I recommend checking out the dedicated Symfony UX component for dependent form fields. Here is the link: Symfony UX Dependent form fields documentation

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Difficulty with NodeJS, Hapi, and Cascading Style Sheets

I've decided to challenge myself by creating a small webhost using Node.js with hapi. Even though I'm not an expert in Node.js, I am eager to learn as much as possible. Currently, my main issue revolves around fetching a CSS file from an include ...

Protractor: Unable to reach variables within closure set in the parent function

I have a code snippet in one of my JS files that looks like this: // test/lib/UserHelper.js 'use strict'; var Firebase = require('firebase'); exports.createUser = function (email, password) { browser.executeAsyncScript(function (do ...

Displaying elements in Angular based on their height

I'm currently working on a paragraph that adjusts its length based on the maximum height. I'm interested in finding a way to display or hide the anchor element if the height exceeds a specific limit. Essentially, I only want to show "more..." whe ...

Error Message: Unhandled TypeError - Unable to access property 'setState' as it is null in React

Encountering an issue on my React page where I receive the error: Uncaught TypeError: Cannot read property 'setState' of null specifically when trying to use the counter component. The problem seems to originate from the usage of this inside th ...

Application utilizing Meteor to connect with external websites or applications

Hey everyone, I'm in the process of developing an application that features a directory of stores. One key requirement is that each store has a unique view created with either Flash or JavaScript. The special view components have already been develope ...

Incorporate a for loop in Javascript to add a variety of items (object1, object2, and object3) to an array

Currently, I am facing a challenge in my project where I need to fetch data from an open-source API. The issue lies in the fact that the API provides objects that must be grouped into an array named ingredients. These objects are labeled as strIngredients1 ...

What is the method for toggling the credentials flag to disable?

It seems like such a simple question, but I am struggling to find the answer which makes me wonder if I don't have control over the flag. Background: I am in the process of developing a SignalR hub and client. Everything works perfectly when I set t ...

Encountering an issue with Firebase Cloud Messaging

I am struggling to implement a push notification trigger whenever a document field is updated. As a newcomer to node.js, I am facing challenges in debugging what seems like a simple function. Below is the code snippet: // Cloud Functions for Firebase SDK ...

The use of $scope.$destroy may resolve memory leak issues, but it can also cause

In my TypeScript AngularJS application, I have a child directive that is dynamically generated. The template and controller are assigned at runtime based on the requirements of the situation, with multiple directives within the template. To display multipl ...

Can you please share a method for exporting multiple slices from a single slice file in redux-toolkit?

I'm relatively new to working with redux and I've been using redux-toolkit lately Is it possible to export multiple slices from a single slice file in redux-toolkit? For example: import { createSlice } from '@reduxjs/toolkit'; const ...

Postponing the initial display of a webpage

I am working with a web application from a different company that has some customization options limited to CSS and allows me to add HTML content at certain points in the code. However, I need more flexibility than what CSS can offer, so I have resorted t ...

Tips for successfully passing module inputs when calling it from the index.js file

Currently, I am in the process of developing custom plugins for a particular product that relies on a proprietary npm module to establish connections and perform various operations (such as reading, writing, and submitting) on a mainframe emulator. In my ...

Calculate the total values of nested objects within an array of objects

I encountered an array of objects with various properties - [{ title: "oranges", id: 5802537, cart: { purchased: 3, stockTotal: 9 }, price: 3, department: "fresh fruit and veg" }, { title: &qu ...

Having Trouble Concatenating Two Parameters in a JavaScript Function

I am attempting to retrieve 2 numbers as arguments for the function saveQuestion, however, I'm encountering an issue. $("#questionRow") .append('<input type="submit" class="btn btn-default" id="saveQuestion' + addSectionCount + & ...

What is the best way to incorporate this code snippet into an object's value?

Is there a way to merge the headStyles object into the headText object? I have already injected the headStyles object into headConfig. import { makeStyles } from '@material-ui/core' const headStyles = { backgroundColor:'green', ...

Tips for preventing useEffect from triggering a route?

Recently delving into reactjs, I stumbled upon a situation in the code where the route alerts messages twice. I'm seeking advice on how to prevent this issue, please disregard the redux code involved. Any suggestions? Index.js import React from &apos ...

Creating a Vue select list by populating it with an array of options and automatically selecting one based on an asynchronous response

I've been experimenting with Vue to create a select list using a predefined array of options. However, when a specific async response or event contains an assignee, I set that as the 'currentAssignee' which is then preselected in the list. ...

Gathering all posts related to jagi astronomy

Within my MongoDB database, I have a collection called "post." My goal is to extract all post IDs that are not disabled from this collection. To achieve this, I utilized Jagi Astronomy, a Meteor JS package, to create the schema. However, when I implemented ...

Adding AngularJS to Syncfusion grid or making the rows clickable and running AngularJS functions can be achieved by following these steps

I'm currently incorporating angularJs and Syncfusion to display data in a table using the Syncfusion grid (). However, I'm encountering difficulties in utilizing angularjs functions within this grid: <div class="table-responsive grid-tog ...

incorrect path in post request

I encounter a dilemma when using a form to edit and update data via ajax in my application. The form can be used for both creating and updating records, which is determined by a ViewBag variable in the view like so: <form asp-action=@(ViewBag.Mode == " ...