Storing form data efficiently with a single key and multiple values using a POST API request

I've encountered a challenge while trying to save form data in a format where there's the same key but different values separated by commas. While I can successfully submit form data via POST for single "key/value" pairs, I'm struggling with handling "key/multiple(values)" pairs.

Would appreciate any insights or suggestions on this matter.


 async handleSubmit(event) {
        event.preventDefault();
        const token = localStorage.getItem("token");
        let url = "https://api/slef_domain/assign_dId/?";
        var form = new FormData();
        form.append("sourcedomainID", this.state.sourceDomID);
        form.append("destInfra", this.state.destInID);
        form.append("destdomainID", this.state.destDomID);
        form.append("domainRangeId", this.state.domainRanID);

        // Need assistance on how to handle multiple values for the same key in the form

        // Here we use the FETCH method to POST data and display the response back on Web.
        await fetch(url, {
            method: "POST",
            body: form,
            headers: { "Authorization": `Token ${token}` },
            "mimeType": "multipart/form-data",
        }).then((results) => {
            return results
        }).then(response => {
            console.log("Actual Response: ", response)
            if (response.status === 204) {
                console.log("Response 204: ", response)
                this.setState({ alertMessage: "Success" })
            }
            else {
                console.log("Response no code: ", response)
                this.setState({ alertMessage: "Unavailable" })
            }
        });
    }

Answer №1

If you are working with PHP on your server, you have two options for handling data like this based on the MDN's example:

form.append('arr[]', 'value1');
form.append('arr[]', 'value2');

Alternatively, you can simply do:

var arr = ['value1', 'value2'];

form.append('arr', JSON.stringify(arr));

Then, use JSON.parse to retrieve your array.

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 state may be modified, but the component remains unchanged

I've been tasked with implementing a feature on a specific website. The website has a function for asynchronously retrieving data (tickets), and I need to add a sorting option. The sorting process occurs on the server side, and when a user clicks a s ...

I'm looking to efficiently convert JSON or GeoJSON data into a Backbone model and then seamlessly transition that model into a Leaflet layer. Can anyone provide guidance on

As I work on refining layer definitions that can be added individually to a collection, my goal is to smoothly render the view or add them to a L.LayerGroup using the leaflet api. However, being new to JavaScript, I am uncertain about how to map the proper ...

What is the best way to display an error message when a necessary field is left empty?

I am currently utilizing a plugin to validate my form. My goal is to display an error message on the button when clicked, as all fields in my form are required and need validation. Despite attempting the code below, it hasn't been successful: <Fo ...

What is the best way to retrieve the current value of a range slider?

Having some trouble with the "angular-ranger" directive that I loaded from a repository. Can anyone assist me in figuring out how to retrieve the current value of the range slider? Any guidance or suggestions would be greatly appreciated! For reference, ...

Error: Unable to load L.GeometryField constructor in django-leaflet library

I'm having trouble saving a geolocation to a Postgres database using Django-leaflet. I keep getting an error message that says Uncaught TypeError: L.GeometryField is not a constructor. My code involves AJAX calls. <script> var csrftoke ...

Issue with 'for' loop iteration over object array

Can someone help me understand why I am getting the unexpected result "6 You have not watched undefined undefined" in the browser console when running this simple code? var films = [{ title: "The Mummy", hasWatched: true, stars: "5 stars" ...

There appears to be a malfunction in the socket rooms, as they are not operating

I have set up a code where sockets are being sent to the wrong person, and I am unable to figure out why. Whenever I update one user's status, it also updates the other user's status. Snippet of Code io.on('connection', function(socke ...

Effective ways to check for the time discrepancy between dates in moment.js

My server is set to use UTC date format and I am running my node server in UTC as well. I am looking to determine if the current time in Indian timezone (which is +5.30) is greater than 8AM, and if so, send an email notification. How can I achieve this u ...

Issues with the functionality of the WordPress plugin

The issue with Spin360: All scripts are linked in functions.php add_action('wp_footer', 'add_scripts'); function add_scripts() { if(is_admin()) return false; wp_deregister_script('jquery'); wp_enqueue_script ...

Resolving the Angular5 (Angular Universal) problem with page source visibility

Currently tackling a server-side rendering project, inspired by the Angular Universal guide. Everything seems to be on track, but I'm facing an issue where even when navigating to different routes, the source code for the initial page is displayed whe ...

Origin Access-Control-Allow Not Recognized

Currently, I am developing a node.js app and have encountered a strange issue: This particular Angularjs snippet... // delete hosts $scope.delete = function(row) { var rowData = { hostname: row.hostname, ipaddr: row.ipAddress, ...

Error: Trying to access the 'keyboard' property of an undefined object

I am encountering an error message 'Cannot read property 'keyboard' of undefined' and I'm not sure how to fix it. I just want to check if the keyboard is visible on the screen, but this specific line of code seems to be causing the ...

Leveraging ES6 with jQuery in Symfony 4

Currently working on a simple app using Symfony 4 and trying to add custom triggers in JavaScript. Having trouble getting my additional code to work as expected, even though it's compiled by Webpack via encore. It seems like my event is not triggering ...

AngularJS's ng-click function seems to be malfunctioning

Currently, I am in the process of learning angularJS with the help of the book titled "Learning Web Development with Bootstrap and AngularJs." One challenge I am facing is creating a ng-click functionality for a button in my project. Unfortunately, when I ...

Embarking on your journey with the Withings API

How can I connect to my website with the Withings API? I want to send weight values to the Withings API and receive body measurement values. Where can I find the code for the Withings API? $config['withings_settings']['widgets'] = &apo ...

Navigating a Bootstrap modal using arrow keys for scrolling - up and down

I attempted to address this issue by using the following code: // here, 'this' represents the modal $(this).focus(); Despite trying the above solution and even attempting to trigger a click event on it, I was unable to get it to work! UPDATE ...

Implementing the React Router into a ReactJS project: Methods to prevent users from clicking on links within React-Router's <Link> component

I'm exploring React-Router's Link and have set up the following: <Link to={...}>{this.props.live? "Live": "Not Live"}</Link> In this configuration, if this.props.live is present, I want to display the text "Live" which will lead to ...

After the rendering process, the React Component member goes back to a state of

One issue I encountered is related to a component that utilizes a separate client for making HTTP requests. Specifically, when trying to use the client within a click event handler, the call to this.client.getChannel() fails due to this.client being undefi ...

The Bar Graph Transition in d3 is Running Backwards

Learning to code has been a fascinating journey for me, but I must admit that JavaScript presents a unique challenge. Currently, I am working on creating a d3.js Bar Chart and I wanted to include a transition effect when the bars load. However, I have enco ...

When attempting to utilize a global variable in a POST request, it may be found to

My dilemma is that I can successfully access the global variable in other requests such as 'GET', but it becomes undefined when used in a 'POST' request. var dirName; app.post("/addFace", function (req, res) { //create directory con ...