How can I get the data of form on submit? - javascript

How can I get the data of form on submit?
import React, { Component } from 'react';
import Axios from 'axios';
class Register extends Component {
submitHandler = (event) => {
event.preventDefault();
var url = '';
var data = {
returnSecureToken:true,
email:this.email,
password:this.password
}
Axios.post(url,data)
.then(response => {
console.log(response);
})
.catch(err =>{
console.log(err);
})
}
render() {
var listClasses = "";
return(
<div>
<h1>Registrati</h1>
<form onSubmit={this.submitHandler}>
<input type="password" className={listClasses} value={this.props.value} placeholder="password" name="password"/>
<input type="email" className={listClasses} value={this.props.value} placeholder="email" name="email"/>
<input type="submit" value="submit"/>
</form>
</div>
);
}
}
export default Register;
I want to send my data by post. I tried to find into my object this but I don't see my data after submit.

The best way to do it is to make the component, uncontrolled component and hook up the change event handlers for each field.
Would be better than using refs that break the encapsulation.
import React, { Component } from 'react';
import Axios from 'axios';
class Register extends Component {
state = {
emailAddress: '',
password: ''
}
submitHandler = (event) => {
const {
emailAddress,
password
} = this.state;
event.preventDefault();
var url = '';
var data = {
returnSecureToken: true,
email: emailAddress,
password: password
}
Axios.post(url, data)
.then(response => {
console.log(response);
})
.catch(err => {
console.log(err);
})
}
handlePasswordChange = (event) => {
this.setState({ password: event.target.value });
}
handleEmailChange = (event) => {
this.setState({ emailAddress: event.target.value });
}
render() {
var listClasses = "";
return (
<div>
<h1>Registrati</h1>
<form onSubmit={this.submitHandler}>
<input onchange={this.handlePasswordChange} type="password" className={listClasses} value={this.props.value} placeholder="password" name="password" />
<input onchange={this.handleEmailChange} type="email" className={listClasses} value={this.props.value} placeholder="email" name="email" />
<input type="submit" value="submit" />
</form>
</div>
);
}
}
export default Register;

Related

where to call the Axios post request in reactjs

I have a form,thats data are saved in the state to be sent to the backend server.
i am handling the form with handleSubmit function and useEffect hook, where the handleSubmit prevents the form from being submitted unless it calls the validation function, in the useEffect I check if there are any errors using if condition and then console.log my data.
now I want to post the data hold in the state -the state is sent as a props to me- but I am confused whether to put the request in the HandleSubmit function or in the useEffect inside the body of the if condition.
import react, { Component, useState, useEffect } from 'react';
import {useNavigate } from 'react-router-dom';
import axios from 'axios';
import './sign.css';
const SignA = (props) => {
const navigate = useNavigate();
const [formErrors, setFormErrors] = useState({});
const [isSubmit, setIsSubmit] = useState(false);
const handleSubmit = (err) => {
err.preventDefault();
setFormErrors(validate(props.data));
setIsSubmit(true);
}
useEffect(() => {
console.log(Object.keys(formErrors).length);
if (Object.keys(formErrors).length === 0 && isSubmit) {
console.log('console the props data', props.data)
//here is where I think the post request should be put
if (isSubmit) {
return (navigate('/profileadmin'))
}
}
}, [formErrors])
const validate = (values) => {
const errors = {};
const regex = /^[^\s#]+#[^\s#]+\.[^\s#]{2,}$/i;
if (!values.firstname) {
errors.firstname = 'firstname is required!';
}
if (!values.lastname) {
errors.lastname = 'lastname is required!';
}
if (!values.mobile) {
errors.mobile = 'mobile is required!';
}
if (!values.email) {
errors.email = 'email is required!';
} else if (!regex.test(values.email)) {
errors.email = 'this is not a valid email format!'
}
return errors;
}
return (
<div className='signup'>
<form onSubmit={handleSubmit} >
<div className="container">
<h1>Sign Up</h1>
<div className="name">
<div>
<input
type="text"
placeholder="First name"
name="firstname"
id='firstName'
value={props.data.firstname}
onChange={props.change}
/>
</div>
<div>
<input
type="text"
placeholder="Last name"
name="lastname"
value={props.data.lastname}
onChange={props.change}
/>
</div>
</div>
<p className='errorMsg'>{formErrors.firstname}</p>
<p className='errorMsg'>{formErrors.lastname}</p>
<br />
<div>
<input
type="text"
placeholder="Business mobile number"
name="mobile"
value={props.data.mobile}
onChange={props.change}
/>
<p className='errorMsg'>{formErrors.mobile}</p>
<br />
<input
type="text"
placeholder="Email Adress"
name="email"
value={props.data.email}
onChange={props.change}
/>
<p className='errorMsg'>{formErrors.email}</p>
<br />
</div>
</div>
<br />
<div className="checkbox">
<label>
<input type="checkbox" className="check" />i’ve read and agree with <a href="url" >Terms of service</a>
</label>
</div>
<div className="clearfix">
<button type="submit" className="signupbtn">Sign Up</button>
</div>
</div>
</form >
</div >
)
}
export default SignA;
this is the request
axios.post('', props.data)
.then(res => console.log('post res', res))
.catch(error => {
console.error('There was an error in post request!', error);
});
You don't necessarily need useEffect here.
Here is how you can implement such thing:
Declare a state to hold form values:
const [formData, setFormData] = useState({})
Declare function to set the state:
const handleChange = (name, value) => {
setFormData({...formData, [name]: value})
}
Input onChange to capture:
// handleChange has two parameters
<input
type="text"
placeholder="First name"
name="firstname"
id='firstName'
value={props.data.firstname}
onChange={(event) => handleChange('firstName', event.target.value)}
/>
function for calling post axios post request
const handleSubmit = () => {
//check for validations code here
// if validations are right then post request here
// this will give you all the fields like firstName: "", lastName: ""
let requestBody = {
...formData
}
axios.post("url", requestBody).then((res)=> {
//your code here
})
}

Not able to get response while sending my data to backend in reactjs

I am using axios for sending my data using POST method.
This axios is not giving me response on the console.
Since, I have also used promise but still not able to get the response on console.
Notice: I am getting the data which I sent...flow of control is not entering into then() promise.
import "./SignUp.css";
import React, { Component } from "react";
import "../SignIn/SignIn.css";
import Organization from "../../Organization/organization";
import axios from "axios";
import { withRouter } from "react-router";
export class SignUp extends Component {
constructor() {
super();
this.state = {
firstName: "",
lastName: "",
password: "",
email: "",
organizationName: "",
};
this.handleFirstNameChange = this.handleFirstNameChange.bind(this);
this.handleLastNameChange = this.handleLastNameChange.bind(this);
this.handlePasswordChange = this.handlePasswordChange.bind(this);
this.handleOrganizationNameChange = this.handleOrganizationNameChange.bind(
this
);
this.handleSubmitLogin = this.handleSubmitLogin.bind(this);
this.handleEmailChange = this.handleEmailChange.bind(this);
}
handleFirstNameChange(event) {
this.setState({ firstName: event.target.value });
}
handleLastNameChange(event) {
this.setState({ lastName: event.target.value });
}
handleOrganizationNameChange(event) {
this.setState({ organizationName: event.target.value });
}
handlePasswordChange(event) {
this.setState({ password: event.target.value });
}
handleEmailChange(event) {
this.setState({ email: event.target.value });
}
async handleSubmitLogin() {
var organizationRecord = new Organization(
this.state.firstName,
this.state.lastName,
this.state.password,
this.state.email,
this.state.organizationName
);
const data = {
First_Name: organizationRecord.getFirstName,
Last_Name: organizationRecord.getLastName,
Password: organizationRecord.getPassword,
Email: organizationRecord.getEmail,
Organization_Name: organizationRecord.getOrganizationName,
};
// Code Starts here
try {
axios
.post("http://localhost:8000/Organization", data)
.then((result) => {
console.log(`Status Code: ${result.status}`);
})
.catch((err) => {
console.error(err);
});
sessionStorage.clear();
sessionStorage.setItem(
"email",
JSON.stringify(organizationRecord.getEmail)
);
this.props.history.push("/sign-in/redirect");
} catch (error) {
console.error(error);
}
//Code ends here
}
render() {
return (
<div className="sign-up-container">
<div className="sign-in-input">
<h2>SIGN UP</h2>
<div className="sign-in-input-inner">
<input
className="input"
value={this.state.firstName}
onChange={this.handleFirstNameChange}
type="text"
placeholder="First Name"
/>
<input
className="input"
type="text"
value={this.state.lastName}
onChange={this.handleLastNameChange}
placeholder="Last Name"
/>
<input
className="input"
type="email"
value={this.state.email}
onChange={this.handleEmailChange}
placeholder="Email"
/>
<input
className="input"
type="text"
value={this.state.organizationName}
onChange={this.handleOrganizationNameChange}
placeholder="Organization Name"
/>
<input
className="input"
type="password"
value={this.state.password}
onChange={this.handlePasswordChange}
placeholder="Password"
/>
<div
onClick={this.handleSubmitLogin}
className="sign-in-button-container sign-up-button-container"
>
Submit
</div>
</div>
</div>
</div>
);
}
}
export default withRouter(SignUp);
Can anyone explain me where I am lagging?

React form onSubmit function not being called

I have a form on my page with an onSubmit function that I want to be called, but it doesn't seem to be triggered as the console.log never appears.
import React, { Component } from 'react'
class EmailSignUp extends Component {
constructor(props) {
super(props)
this.state = {
email: '',
lastName: '',
error: false
}
this.handleChange = this.handleChange.bind(this)
this.onSubmitForm = this.onSubmitForm.bind(this)
}
onSubmitForm (e) {
console.log('function has run');
e.preventDefault()
let formData = new FormData(e)
const { formAction } = this.props
const requestOptions = {
method: 'POST',
body: formData
}
fetch(formAction, requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error))
}
handleChange (e) {
const value = e.target.value
const inputId = e.target.id
this.setState(() => ({
[inputId]: value
}))
}
render () {
const { error } = this.state
return (
<div id='email-form' className='container'>
<form
name='form'
id='form'
onSubmit={this.onSubmitForm}
method='post'
>
<div className='form-group'>
<label htmlFor='email'>Email</label>
<input
type='email'
name='Email'
className='form-control'
id='email'
placeholder='youremail#email.com'
onChange={this.handleChange}
value={this.state.email}
required
/>
</div>
<div className='form-group'>
<label htmlFor='lastName'>Last name</label>
<input
type='text'
name='lastName'
className='text form-control'
id='lastName'
placeholder='Last Name'
onChange={this.handleChange}
value={this.state.lastName}
required
/>
</div>
<button
type='submit'
name='Submit'
value='Subscribe'
className='btn btn-primary item_cta'
readOnly
/>
</form>
{error && <p>{error}</p>}
</div>
)
}
}
export default EmailSignUp
Running your code results in the error 'Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'. The actual form element would be on target of the submit event. Try the following by updating e to e.target:
let formData = new FormData(e.target);
const { formAction } = this.props;
Also remove method from the form element. In addition, remove readOnly from button. It is not meant to be a self closing element like a br:
<button
type="submit"
name="Submit"
value="Subscribe"
className="btn btn-primary item_cta"
>submit</button>
Hopefully that helps!

How can I redirect to correct page when successfully submitting form information?

As of now, I'm successfully inserting information into the database (SQL, phpMyAdmin) via Home.js but the problem is that every time the user enters information & hits submit, it gets redirected to my demo.php file (not provided) instead of Next.js.
In other words, how can I make it so that upon the user information successfully entering the database and go to the next page? (Next.js)?
What am I doing wrong and how can I fix this?
Here's Home.js:
import React, { Component } from 'react';
import Next from '../Home/Next';
class Home extends Component {
constructor(props) {
super(props);
this.state = {
show: false
};
this.getPHP = this.getPHP.bind(this);
this.goNext = this.goNext.bind(this);
}
getPHP() {
fetch(`http://localhost/demo_react/api/demo.php`, {
method: 'POST'
}).then(res => res.json())
.then(response => {
console.log('response');
console.log(response);
});
}
goNext() {
this.setState({show: true});
}
render() {
const next = this.state.show;
if(next) {
return <Next/>;
}
return (
<div>
<br/>
<form className="form-control" action="http://localhost/demo_react/api/demo.php" method={"POST"} encType="multipart/form-data">
<input type="text" name="username"/>
<input type="text" name="password"/>
<input type="submit" value="submit" onClick={this.getPHP & this.goNext} name={"submit"}/>
</form>
</div>
);
}
}
export default Home;
Here's Next.js:
import React, { Component } from 'react';
class Next extends Component {
render() {
return(
<h1>made it</h1>
);
}
}
export default Next;
You need to remove the action property from your form and call getPHP() when form is submitted. Also, it's better to have controlled inputs (state of component change when input change). See this for more info: Get form data in Reactjs
<form className="form-control" onSubmit={e => this.getPHP(e)}>
<input type="text" name="username" value={this.state.username} onChange={e => this.setState({ username: e.target.value })} />
<input type="text" name="password" value={this.state.password} onChange={e => this.setState({ password: e.target.value })} />
<input type="submit" value="submit" name="submit" />
</form>
You can access to form values directly in getPHP() method because inputs are now controlled:
constructor(props) {
super(props);
this.state = {
show: false,
username: '',
password: '',
};
}
getPHP(e) {
e.preventDefault();
const { username, password } = this.state;
const formData = new FormData();
formData.append('username', username);
formData.append('password', password );
fetch(`http://localhost/demo_react/api/demo.php`, {
method: 'POST',
headers: new Headers({ 'Content-Type': 'multipart/form-data' }),
body: formData,
})
.then(res => res.json())
.then(response => {
console.log('response');
console.log(response);
this.goNext();
});
}
At the end, you can goNext() when the fetch succeed.

React Router will not redirect based on state

In the code, it reaches the isRegistered function, I know this as I have it console.log state. The state of registered is equal to true. So therefore based on the code it should redirect to /login but it is not.
import React from 'react'
import "./Register.css";
import {BrowserRouter as Route, Redirect, Link} from 'react-router-dom'
const initialUser = {
username: "",
email: "",
password: "",
password2: "",
name: ""
}
class Register extends React.Component {
constructor(props) {
super(props);
this.state = {
user: initialUser,
registered: ''
};
}
onUsernameChange = event => {
this.setState({ username: event.target.value });
};
onNameChange = event => {
this.setState({ name: event.target.value });
};
onEmailChange = event => {
this.setState({ email: event.target.value });
};
onPasswordChange = event => {
this.setState({ password: event.target.value });
};
onPassword2Change = event => {
this.setState({ password2: event.target.value });
};
isRegistered() {
const { registered } = this.state;
console.log(registered, 'here', this.state)
if (registered) {
return (
<Redirect to='/login' />
)
}
}
onRegister = () => {
fetch("http://localhost:3000/register", {
method: "post",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
name: this.state.name,
email: this.state.email,
username: this.state.username,
password: this.state.password,
password2: this.state.password2
})
})
.then(res => res.json())
.then(data => {
console.log(data.isRegistered);
if (data.isRegistered) {
this.setState({registered: true})
this.isRegistered();
}
})
};
render() {
return <div className="login-page">
<div className="form">
<form className="login-form">
<input type="text" placeholder="name" onChange={this.onNameChange} />
<input type="text" placeholder="username" onChange={this.onUsernameChange} />
<input type="text" placeholder="email" onChange={this.onEmailChange} />
<input type="password" placeholder="password" onChange={this.onPasswordChange} />
<input type="password" placeholder="confirm password" onChange={this.onPassword2Change} />
<button className="bluecolor" onClick={this.onRegister}>
Register
</button>
<p className="message">
Have an account? Login
</p>
</form>
</div>
</div>;
}
}
export default Register;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
It reaches all the way to the if statement in isRegistered(). So I assume it is the redirect component that is wrong but I cannot figure it out for the life of me.
//UPDATE
This is now what I have in it
import React from 'react'
import "./Register.css";
import {BrowserRouter as Route, Redirect, withRouter} from 'react-router-dom'
const initialUser = {
username: "",
email: "",
password: "",
password2: "",
name: ""
}
class Register extends React.Component {
constructor(props) {
super(props);
this.state = {
user: initialUser,
registered: ''
};
}
onUsernameChange = event => {
this.setState({ username: event.target.value });
};
onNameChange = event => {
this.setState({ name: event.target.value });
};
onEmailChange = event => {
this.setState({ email: event.target.value });
};
onPasswordChange = event => {
this.setState({ password: event.target.value });
};
onPassword2Change = event => {
this.setState({ password2: event.target.value });
};
isRegistered() {
const { registered } = this.state;
console.log(registered, 'here', this.state)
if (registered) {
this.props.history.push('/login')
}
}
onRegister = () => {
fetch("http://localhost:3000/register", {
method: "post",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
name: this.state.name,
email: this.state.email,
username: this.state.username,
password: this.state.password,
password2: this.state.password2
})
})
.then(res => res.json())
.then(data => {
console.log(data.isRegistered);
if (data.isRegistered) {
this.setState({registered: true})
this.isRegistered();
}
})
};
render() {
return <div className="login-page">
<div className="form">
<form className="login-form">
<input type="text" placeholder="name" onChange={this.onNameChange} />
<input type="text" placeholder="username" onChange={this.onUsernameChange} />
<input type="text" placeholder="email" onChange={this.onEmailChange} />
<input type="password" placeholder="password" onChange={this.onPasswordChange} />
<input type="password" placeholder="confirm password" onChange={this.onPassword2Change} />
<button className="bluecolor" onClick={this.onRegister}>
Register
</button>
<p className="message">
Have an account? Login
</p>
</form>
</div>
</div>;
}
}
export default withRouter(Register);
And this is the main App.js
import React, { Component } from 'react';
import RegisterFull from "./Components/Register/RegisterFull";
import LoginFull from "./Components/Login/LoginFull";
import HomeFull from "./Components/Home/HomeFull";
import FullContact from "./Components/Contact/FullContact";
import './App.css';
import './Components/flex.css'
import {BrowserRouter as Router, Route} from "react-router-dom";
class App extends Component {
constructor(props) {
super(props);
this.state = {
signedIn: false
}
}
loginUser = () => {
this.setState({signedIn: true})
}
render() {
return (
<Router>
<div>
<Route exact={true} path='/' component={HomeFull}/>
<Route path='/contact' component={FullContact} />
<Route path='/login' component={LoginFull} />
<Route path='/register' component={RegisterFull} />
<Route path='/about' component={HomeFull} />
</div>
</Router>
)
}
}
export default App;
You cannot return Redirect element in render like this by invoking another method in component lifecycles or methods.
You need to wrap your component with withRouter HOC which provides history props.
import {BrowserRouter as Route,, withRouter, Redirect, Link} from 'react-router-dom'
export default withRouter(Register);
and if you want to navigate programmatically :
isRegistered = () => {
const { registered } = this.state;
console.log(registered, 'here', this.state)
if (registered) {
this.props.history.push('/login)
}
}
Some improvements in your code you could make. Here is my suggestion. you don't need to bind anything. You are using latest React. How I know? You are doing onUsernameChange = evnet => {} not onUsernameChange(event){}. Overall #Sakhi Mansoor is right.
import React from "react";
import "./Register.css";
import {
BrowserRouter as Route,
withRouter,
Redirect,
Link
} from "react-router-dom";
const initialUser = {
username: "",
email: "",
password: "",
password2: "",
name: ""
};
class Register extends React.Component {
constructor(props) {
super(props);
this.state = {
user: initialUser,
registered: ""
};
}
handleChange = event => {
this.setState({
user: {
...this.state.user,
[event.target.name]: event.target.value
}
});
};
isRegistered = () => {
const { registered } = this.state;
console.log(registered, "here", this.state);
if (registered) {
this.props.history.push("/login");
}
};
onRegister = event => {
event.preventDefault();
fetch("http://localhost:3000/register", {
method: "post",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(this.state.user)
})
.then(res => res.json())
.then(data => {
console.log(data.isRegistered);
if (data.isRegistered) {
this.setState({ registered: true });
this.isRegistered();
}
});
};
render() {
return (
<div className="login-page">
<div className="form">
<form className="login-form" onSubmit={this.onRegister}>
<input
type="text"
placeholder="name"
name="name"
value={this.state.user.name}
onChange={this.handleChange}
/>
<input
type="text"
placeholder="username"
name="username"
value={this.state.user.username}
onChange={this.handleChange}
/>
<input
type="text"
placeholder="email"
name="email"
value={this.state.user.email}
onChange={this.handleChange}
/>
<input
type="password"
placeholder="password"
name="password"
value={this.state.user.password}
onChange={this.handleChange}
/>
<input
type="password"
placeholder="confirm password"
name="password2"
value={this.state.user.password2}
onChange={this.handleChange}
/>
<button className="bluecolor" type="submit">
Register
</button>
<p className="message">
Have an account? Login
</p>
</form>
</div>
</div>
);
}
}
export default withRouter(Register);
Here is a simple example of how to redirect on a button click.Hope this might help you
import React, { Component } from "react";
import { BrowserRouter,Route,Switch } from 'react-router-dom'
class App extends Component {
render() {
return (
<BrowserRouter>
<Switch>
<Route path="/" exact component={Sample}/>
<Route path="/test" exact render={()=>(<p>Test</p>)}/>
</Switch>
</BrowserRouter>
)
}
}
class Sample extends React.Component {
constructor(props) {
super(props)
this.Click = this.Click.bind(this) // you need to bind the method
}
Click() {
this.props.history.push('/test');
}
render() {
return(
<button onClick={this.Click}>Click</button>
)
}
}
export default App;

Categories

Resources