Axios post request to send form data in reactjs

I am using Axios post request to fill all the data but in the backend, it’s giving undefined value for each field in the form I want to know how to post all the data in formData in Axios because it’s giving in empty data in Axios post request. Now I am only getting empty data so how can I store the data from URL params when I am passing in input text fields here problem is only how to set data in Axios.

import React, { useState, useEffect } from "react";

import axios from "axios";


export default function Form() {
  const [sale, setSale] = useState("");
  const [district, setDistrict] = useState("");
  const [billing, setBilling] = useState("");
  const [customer, setCustomer] = useState("");
  const [product, setProduct] = useState("");
  var bodyFormData = new FormData();
  bodyFormData.append("sale", "12");

  bodyFormData.append("district", district);
  bodyFormData.append("billing", billing);
  bodyFormData.append("customer", customer);
  bodyFormData.append("product", product);

  axios({
    method: "post",
    url: "http://localhost:8080/form",

    data: { bodyFormData },
    headers: { "Content-Type": "multipart/form-data" },
  })
    .then(function (response) {
      //handle success
      console.log(response);
    })
    .catch(function (response) {
      //handle error
      console.log(response);
    });
 
  const { search } = useLocation();

  const urlParams = Object.fromEntries([...new URLSearchParams(search)]);

  useEffect(() => {
    console.log(urlParams);
  }, [urlParams]);

  const classes = useStyles();

  const [currency, setCurrency] = React.useState("EUR");

  const handleChange = (event) => {
    setCurrency(event.target.value);
  };
  
  const onSubmit = (data) => console.log("get", JSON.stringify(data));
  //console.log(url);
  return (
    <div>
      <Grid
        container
        container
        direction="column"
        alignItems="center"
        justify="center"
      >
        <Grid item xs={12} lg={6}>
          <Card
            className="p-4 mb-4"
            style={{
              height: 765,
              transform: "rotateX(15deg)",
            }}
          >
            <Container component="main" fixed>
              <CssBaseline />
                <form
                  className={classes.form}
                  noValidate
                  onSubmit={(e) => onSubmit(e)}
                  //onSubmit={handleSubmit}
                >
                  <Grid container spacing={4}>
                    <Grid item xs={12} sm={6}>
                      <TextField
                        type="text"
                        variant="outlined"
                        fullWidth
                        id="sales"
                        label="Sales office"
                        name="sale"
                        autoComplete="lname"
                        onChange={(event) => {
                          setSale(event.target.value);
                        }}
                        defaultValue={urlParams.salesoff}
                      />
                    </Grid>
                    <Grid item xs={12} sm={6}>
                      <TextField
                        type="text"
                        variant="outlined"
                        fullWidth
                        id="billing"
                        label="Billing document"
                        name="billing"
                        autoComplete="lname"
                        onChange={(event) => {
                          setBilling(event.target.value);
                        }}
                        defaultValue={urlParams.billingdoc}
                      />
                    </Grid>
                    <Grid item xs={12} sm={6}>
                      <TextField
                        variant="outlined"
                        type="text"
                        fullWidth
                        id="district"
                        label="Sales district"
                        name="district"
                        autoComplete="lname"
                        onChange={(event) => {
                          setDistrict(event.target.value);
                        }}
                        defaultValue={urlParams.salesdist}
                      />
                    </Grid>
                  
                    <Grid item xs={12} sm={6}>
                      <TextField
                        variant="outlined"
                        fullWidth
                        id="customer-name"
                        label="Customer name"
                        name="customer-name"
                        autoComplete="lname"
                        onChange={(event) => {
                          setCustomer(event.target.value);
                        }}
                        defaultValue={urlParams.custname}
                      />
                    </Grid>
                   
                    <Grid item xs={12} sm={6}>
                      <TextField
                        variant="outlined"
                        type="text"
                        fullWidth
                        id="name"
                        label="Product name"
                        name="product-name"
                        autoComplete="lname"
                        onChange={(event) => {
                          setProduct(event.target.value);
                        }}
                        defaultValue={urlParams.product}
                      />
                    </Grid>
                   
                    
                    <Grid item xs={12} sm={6}>
                      <TextField
                        fullWidth
                        id="outlined-select-currency"
                        select
                        label={
                          <Typography style={{ fontSize: 20 }}>
                            Action expected
                          </Typography>
                        }
                        value={currency}
                        variant="outlined"
                      >
                        {actions.map((option) => (
                          <MenuItem key={option.value} value={option.value}>
                            {option.label}
                          </MenuItem>
                        ))}
                      </TextField>
                    </Grid>
                    <Grid item xs={12} sm={6}>
                      <TextField
                        variant="outlined"
                        type="number"
                        fullWidth
                        id="lastName"
                        label="Price increment"
                        name="lastName"
                        autoComplete="lname"
                      />
                    </Grid>
                  </Grid>
                  <Button
                    type="submit"
                    fullWidth
                    variant="contained"
                    color="primary"
                    className={classes.submit}
                    onClick={Form}
                  >
                    Submit
                  </Button>
                  <Grid container justify="flex-end">
                    <Grid item></Grid>
                  </Grid>
                </form>
              </div>
            </Container>
          </Card>
        </Grid>
      </Grid>
    </div>
  );
}

Also I am attaching a

screenshot where I am passing the fields in nodejs

Welcome, ayush.

I am not sure what is happening here:

var bodyFormData = new FormData();
  bodyFormData.append("sale", "12");

Where is FormData defined, and what is the type of bodyFormData? Are you sure there is an append method on it that is doing what you expect?

Why not stick with a simple object:

const myResponseBody = {
  district,
  billing,
  customer,
  product
};
1 Like

I assume you are trying to read the incoming POST request as JSON (or similar) probably with body-parser.

But as you set your header to be multipart/form-data you need an appropriate loader for it, like multer.

Again, this is an assumption based on the limited information you gave us. :slight_smile:

1 Like

@sky020 I have done by implementing simple object way also didn’t work out for me I want to know is their other methods to get the data in Axios just like FormData that doesn’t work out for me .

@marmiz okay even I am removing multipart/form-data and passing only application/x-www-form-urlencoded then also its not working the problem is here to passing the data in axios format is not working like FormData

Look into what @Marmiz mentioned about how you are parsing the data on your server.

Also, could you provide more information:

  • Where are you reading undefined?
    • If it is on your frontend, then an issue is likely with the data being sent as plain text. Try res.json()
    • If it is on your backend, then it could be an issue with what is mentioned above.

You probably want to populate the formData when you actually want to submit the values, as well as making the actual axios request.

onSubmit = () => {
  // create my formObject
 // axios.post
}

@marmiz I am implementing that way also I want to ask you when creating every variable like this const [sale, setSale] = useState("");field using hooks initially I have put null value but after getting the values in input text fields using this defaultValue={urlParams.salesoff} so after getting the salesoff value I have to update the data in Axios then there I am using FormData method to append the data in Axios hope you have clear what I am trying to say thanks

Here is my codesanbox link i am sharing for better understanding CodeSandbox @Marmiz @Sky020

You either go for uncontrolled inputs, or controlled one: having both is confusing and counter intuitive.

You tell me you want to control your inputs by having

const [val, setVal] = React.useState();

But then you want to use defaultValue which is primary used on uncontrolled components.


If you want to control the components simply have the default value as your initial setState value

const [val, setVal] = React.useState(props.initialValue)

If this is not clear, then I suggest you to research / ask about React, since it has more to do with it that how you use Axios :sparkles:

1 Like

@Marmiz If I am using defaultValue that is an uncontrolled component then I need an idea of how can I pass that data in Axios post request i.e when the user hits the submit button all the info store in DB.

Nothing different than regular html/js: get the html node value, here you just have the complication of needing a ref from react to get the actual node.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.