Trying to post data using axios and formData but it's empty

Viewed 6209

I'm using Vue3 and axios to post a form using FormData, but it's empty, nothing is being passed.

{"formData":{}}

Here's what I am doing:

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

axios.post("postform",  formData);

I also tried this:

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

and this:

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

But no success. There's no errors, it's just empty.

I retrieve them in PHP like this:

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

So my question is:

How do I post data using FormData?

3 Answers

If you are not sending any file (or your form is not maltipart/form-data) you can use following method to send data through axios:

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

EDIT:

If you are sending any files then in my case following 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'
    }
})

You can convert your FormData Object to simple object and then send that object to server.

const formData = new FormData();
formData.set("key1", "value1");
formData.set("key2", "value2");

let data = {};

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

axios.post("postform",  data);
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import Footer from './Footer';
import Header from './Header';
import Map1 from './img/google-map.png';
import Map2 from './img/google-map-2.png';

const Forms = () => {
   
  const [name, setCompanyName] = useState('')
  const [address, setAddress] = useState('')
  const [phone, setContact] = useState('')
  const [company_logo, setLogo] = useState('')
  const [website, setWebsite] = useState('');
  const [faceBook, setFacebookUrl] = useState('');
  const [instagram, setInstagramUrl] = useState('');
  const [twitter, setTwitterUrl] = useState('');
  const [location, setLocation] = useState('');
  const [city, setCity] = useState('');
  const [google_map_location, setGoogleLocation] = useState('');
  const [momo_number, setMomoNumber] = useState('')
  const [account_type,setAccount] = useState('');
  const [industry_uuid, setIndustry] = useState('');
  const [momo_acct_name, setMomoName] = useState('');
  const [background, setBackground] = useState('');
  const [country_uuid, setCountryId] = useState(null);
  const [accountList, setAccountList] = useState(null);
  const [industryList, setIndustryList]=useState(null);
  const [gps, setGps] = useState('');
  const [token, setToken]=useState(null);


  useEffect(() => {
      

    axios.get('https://rosmallonline.com:7070/ecoms-api/setup/get_countries/')
      .then(res => {
        console.log(res.data.country[0].country_id);
        const countryid = res.data.country[0].country_id;
        setCountryId(countryid);
      })
      .catch(console.log)
    
      axios.get('https://rosmallonline.com:7070/ecoms-api/setup/get_industries/')
      .then(res2 => {
        console.log(res2.data);
        setIndustryList(res2.data.industries);
      })
      .catch(console.log)
  
      axios.get('https://rosmallonline.com:7070/ecoms-api/setup/get_account_types/')
      .then(res3 => {
        console.log(res3.data);
        setAccountList(res3.data.account_types);
      })
      .catch(console.log)

      setToken(sessionStorage.getItem('token'));
  },[])




  const  submitHandler = async (e) => {
    e.preventDefault();

    const formData = new FormData();
    formData.append('file', company_logo, 'company_logo');
    formData.append('name', name);
    formData.append('address', address);
    formData.append('phone', phone);
    formData.append('industry_uuid', industry_uuid);
    formData.append('country_uuid', country_uuid);
    formData.append('account_type', account_type);
    formData.append('city', city);
    formData.append('social_media',{
      'faceBook':faceBook,
      'instagram':instagram,
      'twitter':twitter
    });
    formData.append('background', background);
    formData.append('location', location);
    formData.append('website', website);
    formData.append('gps', gps);
    formData.append('google_map_location', google_map_location);
    formData.append('momo_number', momo_number);
    formData.append('momo_acct_name', momo_acct_name);

   
    await axios.post('ecoms-api/company/update_company_profile/', 
      formData
    ,{
      headers: {
        'Content-Type': 'multipart/form-data',
        'X-COMPANY-USER-AUTH': token
     }
    }).then(response => {
      console.log(response);
      if(response.data.status === 200){
        alert(response.data.message)
    } else {
        alert(response.data.message)
    }
    });
           
  }


        return (
            <div className="page">
        
      </div>

        );
    }


export default Forms;

Related