Issue with Symfony: form fields not being submitted properly after an ajax call

I have a form that includes 3 select boxes. The options in the second select box depend on the selection made in the first select box, and the options in the third select box depend on the selection made in the second select box. I am using ajax to dynamically populate the options in the second and third select boxes. However, after submitting the form, the values of the second and third selects are not being posted.

Below is my FormType:

public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('Typ', EntityType::class, array(
                'class' => 'AppBundle:MaterialTypes',
                'placeholder' => 'Choose an option'
            ))
            ->add('Kategorie', ChoiceType::class, array(
                'placeholder' => 'Choose an option',
                'mapped' => false,
                'choices'  => array(),
                'choices_as_values' => false
            ))
            ->add('Bezeichnung', ChoiceType::class, array(
                'placeholder' => 'Choose an option',
                'mapped' => false,
                'choices'  => array(),
                'choices_as_values' => false
            ))
            ->add('anzahl',null, array('required'=> true))
            ->add('Preis',null, array('required'=> true));
        $builder->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) {
            $event->stopPropagation();
        }, 900);
    }

Additionally, this is the Ajax call I am making:

var typeId = $('#Typ').val();
$.post( "/app_dev.php/material/"+typeId,
function( data ) {
    $('#Kategorie').empty();
    $('#Bezeichnung').empty();
    var result = JSON.parse(data);
    var options ='<option value="" disabled selected>Choose an option</option>';
    for (var i = 0; i < result.length; i++) {
        options +='<option value="'+result[i]['id']+'">'+result[i]['name']+'</option>'
    }
    $('#Kategorie').append(options);
});

While the type (first select) is successfully posted, the selections in the other two selects are not being submitted. What could be causing this issue?

Answer №1

Make sure to refer to the documentation for details on how to use jQuery.post. The second argument should contain the data to be sent via POST, which can be a plain object or a string.

Consider utilizing Twig's path() function to avoid having to rewrite code later on:

var typeId = $('#Typ').val();

var url = '{{ path('your_route_name', {'type': '__TYPE__'}) }}';

url = url.replace('__TYPE__', typeId);

$.post(
    url,
    $("#yourForm").serialize(),
    function( data ) {
        $('#Kategorie').empty();
        $('#Bezeichnung').empty();
        var result = JSON.parse(data);
        var options ='<option value="" disabled selected>Choose an option</option>';
        for (var i = 0; i < result.length; i++) {
            options +='<option value="'+result[i]['id']+'">'+result[i]['name']+'</option>'
        }
        $('#Kategorie').append(options);
    }
);

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

Redirecting pages using an Ajax script in JavaScript

Unfortunately, I am unable to use a *.php extension for my page due to unforeseen circumstances. This has led me to consider using *.html instead and implementing conditional redirection using javascript/Ajax to call a PHP script that can evaluate the cond ...

Guide on implementing a progress bar for file uploads with JavaScript and AJAX request

I am looking to implement a progress bar in my file uploader. Below is the ajax call I have set up for both file upload and progress tracking. $(function() { $('button[type=button]').click(function(e) { e.preventDefault(); ...

Updating a jQuery variable through an AJAX request

Is there a way to update a variable that is located outside of an AJAX call from an event that is inside this AJAX call? This snippet of code shows that the var units is initially set to metric, but when a selectbox changes (inside the AJAX call), I want t ...

Issue: Child actions in ASP.NET MVC 3 with Razor are not permitted to execute redirect actions

After coming across this specific question on SO, I thought it might hold the answer to my problem. However, it didn't quite do the trick. The issue arises with my ASP.NET MVC 3 + Razor application running smoothly on IIS5 on my development PC and th ...

Tips for including a hashtag in an AJAX request

When using ajax to send messages to the server in my chat application, I encountered an issue where everything after a hashtag is omitted. I attempted to address this by encoding the message, but it resulted in other complications in the PHP code. The enco ...

JavaScript JQuery alert popup fails to display

I have been attempting to create an alert pop-up using JQuery that will display when a user clicks on submit without filling out the form. However, when I test my code by leaving the form empty and clicking 'submit', the page just refreshes with ...

Ajax-enabled pre-resize feature for efficient multiple file uploads

I'm currently facing an issue with a function that involves pre-resizing and ajax file uploading. I have a FOR loop which calls this function, depending on the length of the file input size. The strange thing is, sometimes when I call it multiple time ...

A new update is available for the UpdatePanel and ModalPopup Extender

I have structured my form as follows: <asp:Panel runat="server" Id="xyz"> <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional"> <ContentTemplate> 'Gridview featuring edit and delete options ...

Laravel and jQuery: Seamlessly Uploading Images with AJAX

I have been facing issues while trying to upload photos in Laravel using jQuery AJAX. I keep encountering an error message: The photo must meet the following criteria: - The photo must be an image. - The photo must be a file of type: jpeg, png, jpg, gif, ...

Error message: "Serialization of object to ajax/json cannot be completed

I have encountered an issue while attempting to pass a List MyModel via AJAX/JSON to the controller. I noticed that all the objects are being passed as 'undefined': [Form Post Data] undefined=&undefined=&undefined=&undefined=&un ...

Issues with Jquery Autocomplete feature when using an Input Box fetched through Ajax requests

When a user selects an option from the drop-down list, an input box is dynamically added to the page using AJAX. document.getElementById("input_box").innerHTML ="<input id='ProjectName'/>"; However, there seems to be an issue with jQuery ...

Using Jquery.Ajax to send a pair of arguments to a POST api请求

My controller method has the following structure: [HttpPost] public HttpResponseMessage SaveFunc(ChangeRequest[] changeRequests, string comment) { //perform actions } In this method, a user can save a set of changerequ ...

When attempting to send a GET request to the server, there is no response received, although the

I am having an issue with an ajax request I am sending to my server using jQuery's get function. The request is being sent successfully, as Firebug shows a 200 status code, but the server does not provide any response. Even when I enter the address di ...

I want to retrieve a complete HTML page using an AJAX request

I am trying to retrieve the content of a specific page, but encountering issues when using this function: function getResult() { var url="http://service.semanticproxy.com/processurl/ftfu27m3k66dvc3r43bzfneh/html/http://www.smallbiztechnology.c ...

Once the Ajax request is finished, the cookie deletion function ceases to function

When the website loads, a cookie is generated using PHP before any other content or headers are sent. This is done with the following code: $steam_login_verify = SteamSignIn::validate(); if(isset($_COOKIE['userid'])) { //work with cookie va ...

Tips for executing Cross-Origin-Requests from Firebase Hosting to an AWS Lambda function

Excuse me, I'm still new to web development. I have a basic single-page website hosted on Firebase hosting that retrieves some information from an AWS Lambda function (I didn't use Google Cloud because it didn't support outbound requests fo ...

I'm experiencing a lack of feedback while implementing jQuery/AJAX with JSONP

Attempting to perform a cross-domain request using jQuery/AJAX, I have the code below; $.ajax({ url: "http://www.cjihrig.com/development/jsonp/jsonp.php?callback=jsonpCallback&message=Hello", crossDomain:true }) .done(function( msg ) { alert( ...

Utilize jQuery and AJAX to refresh functions after each AJAX call for newly added items exclusively

I have encountered an issue with my jQuery plugins on my website. Everything functions smoothly until I load new elements via AJAX call. Re-initializing all the plugins then causes chaos because some are initialized multiple times. Is there a way to only i ...

Display loading spinner and lock the page while a request is being processed via AJAX

Currently, I am working on a project using MVC in C#, along with Bootstrap and FontAwesome. The main objective of my project is to display a spinner and disable the page while waiting for an ajax request. Up until now, I have been able to achieve this go ...

The JSON file failed to load

Having some trouble running the JSON file with jQuery AJAX, always getting an error message. I am trying to run the code locally without any ASP.NET or PHP, aiming to run JSON without a server. I have set the URL through IIS on my local machine. JSON: / ...