jennifer
jennifer

Reputation: 762

How can I submit forms in an Ajax like way using React and Express?

I have a form I would like submitted. However rather than reloading the page after a submission, I simply want the form submitted in an Ajax like way.

That is, I wan to send the data and the server to respond, but for the page to stay in the browser.

Relevant frond end React code looks like this:

  handleSubmission = (event) => {
    // event.preventDefault();
    console.log('form submitted');
  }


  render () {
    return (
          // ... snip      
          <form onChange = {this.handleChange} onSubmit = {this.handleSubmission} action = "/articles/add" method="POST">

Update:

I found this tutorial here which uses something called FormData as such:

handleSubmit(event) {
    event.preventDefault();
    const data = new FormData(event.target);
    // NOTE: you access FormData fields with `data.get(fieldName)`    
    const [month, day, year] = data.get('birthdate').split('/');
    const serverDate = `${year}-${month}-${day}`;
    data.set('birthdate', serverDate);
    data.set('username', data.get('username').toUpperCase());
    fetch('/api/form-submit-url', {
      method: 'POST',
      body: data,
    });
}

Update:

The React docs on forms show the use of preventDefault but do not show how the actual submission is completed.

Update

MDN cover form submission but does not cover the preventDefault method. See here.

Upvotes: 0

Views: 831

Answers (1)

Ignacio Elias
Ignacio Elias

Reputation: 588

There are several ways of doing this. The react docs do not explain how to do this because it's not reacts'responsibility to do so. You can use the fetch API, as you wrote in the example above, or another library like Axios. How you should format the data you want to send it's up to the server (how the specific route expects the data to be formatted).

Basically, in a submit handle method you should first prevent the default behavior with event.preventDefault(). Then you should get your data formatted correctly to be sent to the server. In React, most forms have an onChange method for every input that keeps updating the state of the component to match the values being put in every input, so at the time you submit your form your data is already stored in the components'state. Finally, you should do the request to the correct URL as a post request and create a callback function for when the server responds. You can do this using async/await or with the function then() used in promises. For the sake of simplicity, we will use then().

EXAMPLE

class NameForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {firstName: '', lastName: ''};

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

  handleChange(event) {
    this.setState({[event.target.name]: event.target.value});
  }

  handleSubmit(event) {
    event.preventDefault();
    const data = this.state;
    fetch(YOUR_URL, { method: 'POST', body: data })
      .then(response => response.json())
      .then(data => console.log(data));
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          First Name:
          <input type="text" value={this.state.firstName} onChange={this.handleChange} />
          Last Name:
          <input type="text" value={this.state.lastName} onChange={this.handleChange} />
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}

Upvotes: 1

Related Questions