Making changes to an object using a popup form and executing an ajax request

Starting my journey with symfony and development, I am faced with the task of editing an object using a form embedded in a popup. Here's how I handle it:

First, I use JavaScript along with AJAX to send the data "id" to locate the object based on its id. Subsequently, I include the form data for modifying this object using the following JS code:

    $('.btn-edit').click( function() {

        $(this).val();
        console.log("edit clicked " + $(this).val());

        let id = $(this).val();
        let DATA = {'id':id};
        let url = '/edit'

        $.ajax({  // Sending a request with player ID as data.
            type: "POST",
            url: url,
            data: JSON.stringify(DATA),
            contentType: "application/json; charset=utf-8",
            dataType: 'html',
            cache: false,
            success: function (data3) { // Editing action result: including form in a popup
                $('#modal_detail').html(data3); // fetching the form
                $('#modal-title').html("Edit Player"); // Displaying Popup Title
                $('#dataModal').modal("show"); // Showing the popup

                // Sending the form data
                $('form').submit(function(e) {
                    e.preventDefault();
                    let $formplayer = $(this);
                    let route = '/edit';
                    let datas = $formplayer.serialize();
                    $.post({
                        type: 'post',
                        url: route,
                        data: datas,
                        success: function(result) {
                            console.log(result);
                            $('.formMessage').addClass('success').html(result);
                            location.replace('/');
                        },
                        error: function(err){
                            $('.formMessage').addClass('success').html(err);
                        }
                    });


                });

            }
        });

    });

Check out my controller code snippet below:

/**
     * @Route ("/edit", name = "edit")
     *
     * @param $request
     *
     * @return RedirectResponse
     *
     * @throws JsonException
     */
    public function editPlayer(Request $request, PlayerRepository $playerRepository): Response
    {
        $em = $this->getDoctrine()->getManager();

        $post_data = json_decode($request->getContent(), true, 512, JSON_THROW_ON_ERROR);
        $id = $post_data['id'];

        $player = $this->getDoctrine()
                ->getRepository(Player::class)
                ->find($id);

        $form = $this->createForm(PlayerFormType::class, $player);

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($player);
            $em->flush();

            return $this->redirectToRoute('player');
        }

        return $this->render('manager_temp/edit.html.twig', [
            'player' => $player,
            'form' => $form->createView(),
        ]);
    }

I suspect an issue in processing user-filled form data within my controller logic. While trying to decode the form data with JSON to extract the id, it seems redundant since I have already sent the id initially...

This dilemma has left me stuck, seeking assistance to untangle this situation. Your guidance would be greatly appreciated!

Answer №1

Surprisingly, it turned out to be quite simple. If you want to include the ID in the URL:

Using AJAX:

const formData = {'id': id};
const url = '/update/' + id;

In your controller:

* @Route ("/update/{id}", name = "update")

This way, you can submit the form data without needing JSON.

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

The backbone module is experiencing formatting issues

I'm new to learning backbone.js. I've created the example below, but unfortunately, it's not functioning properly. Can someone please help me understand why? The goal is to simply display the name within my div element. (function($) { ...

What are the steps to generate an npm package along with definition files?

Is it possible to create an NPM package with definition files containing only interfaces declared in *.ts files? Consider a scenario where we have two interfaces and one class definition: export interface A { id: number; } export interface B { name: s ...

Issue with Angular and Karma: HTTP GET request not running

Currently, I am working on an AngularJS project that utilizes Karma to execute some unit tests directly in the browser. To conduct these tests, I have opted for mocha as the test framework. The challenge I am facing lies in running specification tests tha ...

Issues with GET and POST requests for a specific IP address resulting in an Internal Server Error

I've been working on migrating an application to a new server on Amazon. I set up an EC2 instance, configured it, and installed the application successfully. However, I'm experiencing issues with my ajax requests - they're resulting in an "i ...

Struggling to retrieve the session value using JavaScript in a C# application

Currently, I am attempting to retrieve four values from the session. However, I am only able to fetch two of them, while the other two seem to be missing. As a beginner, I apologize if my question comes across as too simplistic. Within a tree view, I have ...

What's the best way to display alert messages using the alert method in Node.js with Jade?

Is there a way to render a 'Jade view' with data? For example, in the following code: app.get('/', function(req, res){ res.render('alert', {msg: 'hi!'}); }); I attempted to write the Jade code below: (alert.ja ...

Accepting a custom object wrapper containing non-primitive attributes in Spring MVC using @RequestBody

To create the JSON data, I followed these steps: var manager = { username: "admin", password: "admin" }; var userToSubscribe = { username: "newuser", password: "newpassword", email: "<a href="/cdn-cgi ...

Combine a pair of select statements to utilize the RxJS store within an Angular Guard

When working on an Angular Guard, I encountered a challenge where I needed to select two fields from the ngrx store. Here is the code snippet for reference: @Injectable() export class RoleGuard implements CanActivate { constructor( public router: A ...

Deleting tasks from the to-do list using Node.js and Express with EJS

Looking to implement functionality where each list item can be removed from a Node.js array by clicking on an HTML button using EJS and Express: I am considering placing an HTML button next to each list element so that the selected element can be removed ...

Is it necessary to include a promise in the test when utilizing Chai as Promised?

Documentation provided by Chai as Promised indicates the following: Note: when using promise assertions, either return the promise or notify(done) must be used. Examples from the site demonstrate this concept: return doSomethingAsync().should.eventua ...

The Dynamic Data Duo: JSON and Python

Currently, I am in the process of creating a web interface for Arduino using Python, with JSON being utilized for automatic updates and display. However, an intriguing issue has arisen. Within the code snippet below, a command is sent to a python function ...

Tips for generating identical hashes from JSON data

I'm looking to authenticate a JSON payload, but I've encountered an issue with unmarshaling/marshaling potentially changing the order of the JSON properties. This could cause the signature to be invalidated. Is there a method to generate a consi ...

Unable to see text scrolling in the div container

I am trying to manipulate a div that contains some phrases: <div class="container"> <div class="phrase-doc">Lorem ipsum bla bla</div> <div class="phrase-doc">Lorem ipsum bla bla</div> <di ...

Utilizing the dojo.xhrget() Method to Showcase Information in the Dojogrid

Trying to showcase a dataset retrieved asynchronously from the server using the dojo.xhrget() method. The intention is to update the grid with new values each time a user interacts with the content pane, without refreshing the entire page. However, running ...

"Repeatedly encountering 'undefined' when subscribing to the selected option of a select list in Knockout.js

In my dropdown list, I have prepopulated a selection of strings. My select list is bound as follows: <select id="industryDropDown" data-bind="options: $root.orgIndustrySuggestions, value: $root.selectedIndustryTag, optionsCaption: ''"> ...

Is there a way to prevent continuous repetition of JavaScript animated text?

I'm working on a code that displays letters and words one by one, but I can't figure out how to stop it from repeating. Can someone help me with this? <div id="changeText"></div> <script type="text/javascript"> var te ...

What is the best way to conceal a website's URL?

Is it possible to hide the actual URL some.otherdomain.com and show only domain.com to visitors of my website? I am looking for a way to mask the URL, perhaps through .htaccess or javascript. Is there any solution available? ...

Navigating an array and organizing items based on matching properties

When I receive an array that looks like this: errors = [ { "row": 1, "key": "volume", "errorType": "Data type", "expectedType": "number", &quo ...

Challenges arise when attempting to accurately determine the pixel count of animated elements

I'm facing an issue with this code where it doesn't produce any result. The variable is needed since the number varies each time the user clicks. Is it not possible to define the number of pixels in this way? Your help is greatly appreciated. $( ...

Finding and merging duplicate values within a Javascript array

I am working with a dynamically generated array that looks like this: var myArray = ("0% { left:74px; top:202px; }" , "44% { left:427px; top:122px; }", "0% { font-size:11px; }", "55% { font-size:49px; }" ); Within the array, there are 2 entries that ha ...