I am trying to create a login form using React JS as frontend and PHP as backend. I can't seem to figure out how to pass the form's data (email and password) to the PHP script. I tried googling and all the solutions either don't work for me or are out of data. I am using React v16.
This is my front-end code:
import React, { useState } from 'react';
// libraries
import { Col,
Button,
Form,
FormGroup,
Label,
Input} from 'reactstrap';
import Axios from 'axios'
const App = () => {
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const submit = () => {
Axios({
method: 'POST',
url: 'http://localhost:80/api/login.php',
headers: {
'Content-Type': 'application/json',
},
data: {
email,
password
}
})
.then((response) => {
console.log(response)
})
.catch((error) => {
console.log(error)
})
}
return (
<div>
<Form>
<FormGroup row>
<Label for="exampleEmail" sm={2}>Email</Label>
<Col sm={10}>
<Input value={email} onChange={e => setEmail(e.target.value)} type="email" name="email" placeholder="email" />
</Col>
</FormGroup>
<FormGroup row>
<Label for="examplePassword" sm={2}>Password</Label>
<Col sm={10}>
<Input value={password} onChange={e => setPassword(e.target.value)} type="password" name="password" placeholder="password" />
</Col>
</FormGroup>
<FormGroup check row>
<Col sm={{ size: 10, offset: 2 }}>
<Button onClick={submit}>Submit</Button>
</Col>
</FormGroup>
</Form>
</div>
);
}
export default App;
And this is my backend:
<?php
$data = json_decode(file_get_contents("php://input"));
echo "received data";
print_r("$data");
?>
For now, if I look at Chrome inspector, it will say Request Payload is {email: "xxx", password: "xxx"} so I know my front end is trying to send data to login.php but I don't know how to "catch" the data sent by the front end with PHP.
What I intended to do is: once login.php gets the data, it will return a JSON object of the data and the string "received data" back to the frontend.
Please help me take a look at this. I did research all day and still can't find a solution.
FYI, I have been trying every solution I can find online for example I tried this:
let data = {
email,
password
}
let form = new FormData()
form.append('data', data)
Axios.post('http://localhost:80/api/login.php', form)
.then(...)
.catch(...)
and the backend will be:
$email = $_POST['email'];
$password = $_POST['password'];
But to no avail.
URL: 'http://localhost:80/api/login.phpi think something is missing on portlogin.phpon Wamp server and the port is indeed 80