25

I have a dynamic form generated using json data and I need to pass the form input values on submit. I'm planning to send the values as formdata. I have created submit function but i don't know how to append the values in formdata and need to pass through post method using Axios. I'm new to react can anyone tell me how to do this. Below is my code.

var DATA = {
  "indexList": [{
    "Label": "Name",
    "Type": "text",
    "Regex": "",
    "Default_Val": "",
    "Values": {
      "Key": "",
      "Value": ""
    },
    "Validtion Msg": "",
    "Script": "",
    "Mandatory": "Y",
    "maxLength":"16",
    "minLength":"7",
    "format":"Alphanumeric",
    "cssClassName": "form-control",
    "Placeholder": ""
  },
  {
    "Label": "Select Language",
    "Type": "dropdown",
    "Regex": "",
    "Default_Val": "English",
    "Values": [{
      "Key": "option1",
      "Value": "English"
    },{
      "Key": "option2",
      "Value": "Spanish"
    }],
    "Validtion Msg": "",
    "Script": "",
    "Mandatory": "Y",
    "maxLength":"",
    "minLength":"",
    "format":"",
    "cssClassName": "form-control",
    "Placeholder": ""
  },
  {
    "Label": "Type",
    "Type": "radio",
    "Regex": "",
    "Default_Val": "",
    "Values": [{
      "Key": "option1",
      "Value": "Form1"
    }, {
      "Key": "option2",
      "Value": "Form2"
    }, {
      "Key": "option3",
      "Value": "Form3"
    },{
      "Key": "option4",
      "Value": "Form4"
    },{
      "Key": "option5",
      "Value": "Form5"
    }],
    "Validtion Msg": "",
    "Script": "",
    "Mandatory": "Y",
    "maxLength":"",
    "minLength":"",
    "format":"",
    "cssClassName": "form-control",
    "Placeholder": ""
  }
  ]
};

var Menu = React.createClass({

  getInitialState() {
    return {
    }
  },

  _renderElement: function(group){
    switch(group.Type){
      case 'text':
        return (
          <input
            className={group.cssClassName}
            id={group.Label}
            placeholder={group.Placeholder}
            required={group.Mandatory == 'Y' ? true : false}
          />
        );

      case 'dropdown':
        return (
          <select className={group.cssClassName}>
            <option value="">{group.Placeholder}</option>
            {group.Values.map(el => <option>{el.Value}</option>)}
          </select>
        );

      case 'radio':
        return (
          <div className={group.Type}>
            <div for="let value of group.Values">
              {group.Values.map(el=> (
                <label><input name="radios"/>{el.Value}</label>
              ))}
            </div>
          </div>
        );
    }
  },

  renderForm: function () {
    var data = DATA.indexList;
    return data.map(group => {
      return (
        <div>
          <label for={group.Label}>{group.Label}</label>
          <div>
            {this._renderElement(group)}
          </div>
        </div>
      )
    });
  },


  _onSubmit: function () {
    let formData = new FormData();
    var data1 = DATA.indexList;
    data1.map(group => {
      formData.append(group.Label); // How to get the input value here as a second parameter, so than i can pass the label name and corresponding value to form data.
    });

    const config = {
      headers: { 'content-type': 'multipart/form-data' }
    }

    Axios.post('',formData, config)
      .then(response => {
        console.log(response);
      })
      .catch(error => {
          console.log(error);
      });
  },

  render: function() {
    return (    
      <div className="container">
        <br/>
        <div className="panel panel-primary">
          <div className="panel-heading">Form</div>
          <div className="panel-body">
            <form>
              <div className="form-group">
                <div className="col-xs-5">
                  {this.renderForm()}
                  <button type="submit" className="btn btn-primary" onSubmit={this._onSubmit()}>Submit</button>
                </div>
              </div>
            </form>
          </div>      
        </div>
      </div>
    )
  }
});

ReactDOM.render(<Menu/>, document.getElementById('app'));

5 Answers 5

52

To post the FormData using axios, you need specify in header that you are sending FormData, for that content-type should be multipart/form-data.

Check this, how to use FormData with axios:

let formData = new FormData();    //formdata object

formData.append('name', 'ABC');   //append the values with key, value pair
formData.append('age', 20);

const config = {     
    headers: { 'content-type': 'multipart/form-data' }
}

axios.post(url, formData, config)
    .then(response => {
        console.log(response);
    })
    .catch(error => {
        console.log(error);
    });
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the help. I have edited the question with your updated code. I want to pass the input values as second parameter to formdata so that i can see the label and corresponding value in formdata. I tred but Im not able to resolve it.
27

You can access FormData like this:

handleSubmit(event) {
    // Prevent default behavior
    event.preventDefault();

    const data = new FormData(event.target);
    // Access FormData fields with `data.get(fieldName)`
    // For example, converting to upper case
    data.set('username', data.get('username').toUpperCase());

    // Do your Axios stuff here
}

This is the code for the form:

render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label htmlFor="username">Enter username</label>
        <input id="username" name="username" type="text" />
        <button>Send data!</button>
      </form>
    );

1 Comment

can you explain why do you passed this in onSubmit.
0

You can update your changes to your state dynamically. See the example Here

constructor(props) {
    super(props);
    this.state = {value: ''};

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

bind all your fields to your state. Exampkle

this.sate = { name: '', username: '', select: '' }

and then

_renderElement: function(group){
    switch(group.Type){
      case 'text':
      return <input className={group.cssClassName} 
      id={group.Label} 
      placeholder={group.Placeholder}
      value={this.state[group.name]}
      onChange={this.handleUsernameChange}
      required={group.Mandatory == 'Y'? true:   false}/>

      case 'dropdown':
      return <select className={group.cssClassName}>
      onChange={this.handleDropDropDownChange}
      <option value="">{group.Placeholder} </option>
      {group.Values.map(el => <option>{el.Value}</option>)}
      </select>



      </div>
    }
  }

note group.name can be username, name or what ever you name your control.

handleUsernameChange(event) {
    this.setState({username: event.target.value});
  }

handleDropDownChange(event) {
    this.setState({select: event.target.value});
  }

and then when posting

axios.post(url, this.state, config)
    .then(response => {
        console.log(response);
    })
    .catch(error => {
        console.log(error);
    });

Don't forget to update your render to

render: function() {
    return (    
      <div className="container">
      <br/>
      <div className="panel panel-primary">
      <div className="panel-heading">Form</div>
      <div className="panel-body">
      <form onSubmit={this.handleSubmit}>
      <div className="form-group">
      <div className="col-xs-5">


      {this.renderForm()}


             <input type="submit" value="Submit" />
      </div>
      </div>
      </form>
      </div>      
      </div>
      </div>
      )}
  });

Have a look at the doc here https://facebook.github.io/react/docs/forms.html

Comments

0

Using fetch


function uploadFile(file) {
  fetch('https://path/to/api', {
    // content-type header should not be specified!
    method: 'POST',
    body: file,
  })
    .then(response => response.json())
    .then(success => {
      // Do something with the successful response
    })
    .catch(error => console.log(error)
  );
}

1 Comment

it gives syntax error at response.json(). It get fixed after surrounding the statement response.json() with curly braces i.e. {response.json()}
0

Frontend: React handleSubmit function In React, I'm using the following handleSubmit function to submit the form data as URL-encoded:

const handleSubmit = async (e) => {
e.preventDefault();
const formData = new FormData(e.target);
const finalData = Object.fromEntries(formData.entries());

try {
    const resp = await axios.post(
        `${process.env.REACT_APP_API_URL}/${httpservice.uupdate}/${data._id}`,
        new URLSearchParams(finalData).toString(), 
        {
            headers: {
                "Content-Type": "application/x-www-form-urlencoded"
            }
        }
    );
    if (resp) {
        return redirect("/");
    }
} catch (error) {
    console.error("Error submitting data:", error);
}};

Backend: Express.js Setup On the server, I'm using express.urlencoded({ extended: false }) to handle URL-encoded data:

const express = require('express');
const app = express();

app.use(express.urlencoded({ extended: false })); 

app.post('/your-api-endpoint', (req, res) => {
    console.log(req.body); 
    res.status(200).json({ message: "Data received successfully" });
});

app.listen(3000, () => {
    console.log('Server is running on port 3000');
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.