Using React JS to Send User Form Data to PHP API and Store in MySQL – Part 04

Posted by








Post User Form data to API with React JS

Post User Form data to API with React JS

In this article, we will learn how to post user form data to an API using React JS. We will also be using PHP API and MySQL for this example. This will allow us to perform CRUD (Create, Read, Update, Delete) operations using React JS and the backend server.

Setting up the project

First, let’s set up a new React project. You can do this by running the following command in your terminal:


npx create-react-app react-crud
cd react-crud

Once the project is set up, we can start by creating a new component for our user form. You can create a file called UserForm.js and add the following code:


import React, { useState } from 'react';

const UserForm = () => {
const [formData, setFormData] = useState({
name: '',
email: ''
});

const handleSubmit = async (e) => {
e.preventDefault();
try {
const response = await fetch('http://localhost:8000/api/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(formData)
});
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error:', error);
}
}

const handleChange = (e) => {
setFormData({
...formData,
[e.target.name]: e.target.value
});
}

return (




);
}

export default UserForm;

Creating the API and Database

Next, we need to set up a backend server using PHP and MySQL. You can create a new file called api.php and add the following code:


connect_error) {
die("Connection failed: " . $conn->connect_error);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$data = json_decode(file_get_contents('php://input'), true);

$name = $data['name'];
$email = $data['email'];

$sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";

if ($conn->query($sql) === TRUE) {
echo json_encode(['message' => 'User created successfully']);
} else {
echo json_encode(['error' => 'Error creating user']);
}
}

$conn->close();

?>

Make sure to replace the database credentials with your own. You will also need to create a table called users in your MySQL database with the fields name and email.

Integrating the API with React JS

Finally, we can integrate the API with our React JS application by making a POST request from the UserForm.js component we created earlier. When the user submits the form, the data will be sent to the API and added to the database.

Now you have successfully implemented a way to post user form data to an API using React JS, PHP, and MySQL. You can extend this example to include additional CRUD operations and manage the data in your backend server.


0 0 votes
Article Rating
3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
MCA-12- Paresh Singh
7 months ago

Bro mera php file network par shoe ni kar Raha…

patel minesh
7 months ago

Sir data is insert for one time only

AnuragIt vlogs
7 months ago

Bro data insert time p error aa rha network error aor axios ka aa rha