Struggling to send information through axios with formData, but it appears to be devoid of content

I'm currently working with Vue3 and axios to submit a form using FormData. However, I am facing an issue where the form data is empty and not being passed.

{"formData":{}}

Here's my code snippet:

const formData= new FormData();
formData.set("name", name);

axios.post("postform",  formData);

I have also attempted the following approaches:

formData.set("name", "John Doe");
axios.post("postform",  formData);

and this:

formData.append("name", "John Doe");
axios.post("postform",  formData);

Unfortunately, none of these methods have worked for me. There are no errors displayed, but the form data remains empty.

In my PHP code, I retrieve the data like this:

 echo $request->input("name");

Therefore, my main inquiry is:

How can I successfully post data utilizing FormData?

Answer №1

When not sending a file or using multipart/form-data in your form, you can utilize the following approach to send data via axios:

let formData = {};
formData.name =  "John Doe";
axios({
  url: "postform",
  method: "POST",
  data: formData
});

UPDATE:

If files are being sent, this method worked for me:


const formData = new FormData();
formData.append("name", "hello world");



axios({
    url: 'postform',
    method: "POST",
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
})

Answer №2

If you have a FormData Object, you can easily transform it into a simple object and then transmit that data to the server.

const formData = new FormData();
formData.set("username", "johndoe");
formData.set("email", "johndoe@example.com");

let userData = {};

// iterate through the key/value pairs
for(var pair of formData.entries()) {
    userData[pair[0]] = pair[1];
}

axios.post("submitdata",  userData);

Answer №3

To ensure the correct data is sent, consider including the 'Content-Length' header with the value of formData.getLengthSync(). An example of implementing this would be:

const reply = await axios.delete(url, {
  "data": formData,
  "headers": {
    "Content-Length": formData.getLengthSync()
  }
});

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

Leveraging the power of the babel standalone tool to utilize imports in

Trying to execute React in Babel-standalone and implementing imports from neighboring files is my current dilemma. I am inclined to avoid using a bundler and prefer solutions that strictly involve import/export. Below is a brief example of the issue: i ...

Conceal javascript within php

<?php if( isset($_GET['message']) ) { $message = urldecode($_GET['message']); echo "<h2 id='mydivm'>". $message . "</h2>"; ?> <script> setTimeout( function() { ...

Is there a way to programmatically generate a component instance in Vue 3?

I am facing an issue with creating a vue 3 component instance programmatically within a directive. The error message 'tooltip is not a constructor' keeps popping up. Below is the relevant segment of my directive code: import tooltip from ' ...

Monitoring the initiation and completion of web requests within the Ionic framework

Currently utilizing the ionic framework in conjunction with Angular JS. In need of assistance on how to monitor the initiation of a web request. To handle the completion of a request, I have created a directive with an onLoad attribute. Here is the exam ...

Combining two functions in JavaScript to target the same div: a simple guide

Currently, the code below is functioning correctly. However, I am interested in combining the checked and click functions into a single function. Is this possible? $(function () { if($("#enablepromo0").is(":checked")) $("#PromoPanel").show(300 ...

"Stellar.js fails to function properly when applied to elements loaded dynamically through AJAX requests

I recently implemented the amazing Stellar.js for parallax effects in a project of mine. However, I've encountered an issue: Stellar.js does not recognize when I update content via AJAX (specifically loading new div elements from an HTML file and rep ...

Overlooking errors in RxJs observables when using Node JS SSE and sharing a subscription

There is a service endpoint for SSE that shares a subscription if the consumer with the same key is already subscribed. If there is an active subscription, the data is polled from another client. The issue arises when the outer subscription fails to catch ...

Tips for keeping a video background stationary while allowing the text to move smoothly

When I added the video for the background, it only appears at the top of the page. However, I want it to be visible as the rest of the page is scrolled. <div class="hero"> <video autoplay loop muted plays-inline class="back-video&qu ...

Select state and city options similar to the national breakdown page

I'm attempting to replicate a state and city selection box similar to the one on the NTTS Breakdown website. You can see it in action here: When you select a state on the left side of the webpage, the city selection box displays "loading data" and th ...

Can you add a variable to a string once the string has already been formed?

Is there a way to change the quotes of a string from double or single quotes to backticks in JavaScript after it has already been defined? I need to be able to add variables into the string. I attempted using replace(), but it seems like the variable is n ...

What methods can I use to modify strings within JSX?

Within a JSX file, I am faced with the task of manipulating a particular string in a specific manner: Imagine that I have the following string assigned to medical_specialty = "Plastic Surgery" The objective is as follows: medical_specialty.replace(&apos ...

Tips for confirming date is earlier than current date in Reactjs?

Looking for guidance on how to ensure a date selected by a user is always before the current date when using Material UI in my project. For instance, if it's January 6th, 2021 and the user selects either January 5th or 6th that would be acceptable. Ho ...

What is causing this code to keep iterating endlessly?

I have a basic jquery script embedded in my HTML code that utilizes the cycle plugin for jQuery. The problem I'm facing is that when I interact with the slideshow using the "next" or "previous" buttons, it continues to loop automatically after that in ...

No cookie found in the system

Attempting to create an effect using bloom and shaders in post-processing. However, encountering an error in the console with a blank white screen. I have tried clearing cookies, caches, and even running this in incognito mode, but it's still not work ...

Extending the rules and requirements of VInput

Currently, I am utilizing Vue+Vuetify and facing the task of revamping a custom selector component. The existing code structure is as follows: <template> <v-autocomplete :id="id" v-model="internalValue" :clearabl ...

Issue with jQuery .on('change') function not functioning correctly following a row being duplicated

Within my input form, I have implemented an on-click function that triggers an ajax call to submit a table row to the database. Upon submission, the row is then duplicated so that the user can input more data if necessary. The issue I am currently facing r ...

Transforming a file with a node module that lacks a .js class into a browseable format

I am currently working on browserifying my module. One of the dependencies I have is on this https://www.npmjs.com/package/chilkat_win32. It is present in my node_modules folder and here is how the structure looks: https://i.stack.imgur.com/uw9Pg.png Upo ...

Stop all file uploads using jQuery

I have integrated the jQuery File Upload plugin () into my website for image uploads. Here is my code snippet: $('#fileupload').fileupload({ url: 'server/index.php', dataType: 'json', dropZone: $('#dropzone&a ...

Form an array using the values that are returned

As I iterate through an object and extract elements, my console.log displays: ["item 1"] ["item 2"] ["item 3"] and so on. All I want is to create a new array formatted like this: ["item 1","item 2","item 3"]; ...

Tips for sending push notifications to multiple devices via Firebase Cloud Messaging

I was exploring ways to send push messages from my expressJS server to my ionic app and I came across GCM. Using GCM, I could deliver messages by passing a list of tokens like this: sender.send(message, { registrationTokens: deviceTokens }, f ...