Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reactjs: Form action method and onSubmit

I have a situation where I need to submit my form. When I use this method 1

Method 1

<form action="my_redirect_url" method="post" onSubmit={this.registerEmail.bind(this)}>
   <input
     type="text"
     placeholder='Email address'
     name='EMAIL'
     value={this.state.email}
     onChange={this.handleChangeEmail}
   />
   <button type='submit' />
</form>

Then the form submits perfectly but I miss the form validation i.e the email validation part. Its valid or not, the form redirects

Method 2

// onSubmit method
registerEmail = (e) => {
  e.preventDefault();
  let { email } = this.state;
  let emailValidated = validateEmail(email);
  if (emailValidated) {
    fetch('my_redirect_url', {
      method: 'post',
      body : JSON.stringify({
        EMAIL: email
      }),
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      }
    })
    .then(ParseJSON) // It parses the output
    .catch(function(error) {
      console.log("error---", error)
    });
  } else {
    alert("invalid email")
  }
}

// Form
<form onSubmit={this.registerEmail.bind(this)}>
   <input
     type="text"
     placeholder='Email address'
     name='EMAIL'
     value={this.state.email}
     onChange={this.handleChangeEmail}
   />
   <button type='submit' />
</form>

In Method 2, the validation is done correctly but then it doesnot redirects and says an error that Fetch api cannot load 'my_redirect_url' Response for preflight is invalid (redirect)

So whats the issue and how can it be solved?

like image 399
iamsaksham Avatar asked Aug 22 '17 12:08

iamsaksham


1 Answers

If you tell the program to e.preventDefault(), then he won't execute the normal redirect, which we are all waiting for.

So vice versa you have to remove it to redirect the user afterward. Only preventDefault() if the E-Mail is incorrect.

like image 127
marpme Avatar answered Sep 25 '22 08:09

marpme