Skip to content
Related Articles

Related Articles

How to connect ReactJS as a front-end with PHP as a back-end ?

View Discussion
Improve Article
Save Article
Like Article
  • Difficulty Level : Basic
  • Last Updated : 07 Mar, 2022

ReactJS: It is a declarative, efficient, and flexible JavaScript library for building user interfaces. It’s ‘V’ in MVC. ReactJS is an open-source, component-based front-end library responsible only for the view layer of the application. It is maintained by Facebook.

PHP: The term PHP is an acronym for Hypertext Preprocessor. It is a server-side scripting language that is used for web development. It can be easily embedded with HTML files. HTML codes can also be written in a PHP file.

In this article we will learn how to connect React as front-end and PHP as back-end. 

Prerequisite:

Project Setup:

Step 1: Create a React application using the following command:

npx create-react-app folderName

Step 2: After creating your project folder(i.e. folderName), move to it by using the following command:

cd folderName

Step 3: Create a folder named PHP in root to store server files there and create a server.php file.

Project Structure: It will look like this.

Implementation: Write down the code in respective files.

App.js




import { useState } from "react";
import $ from "jquery";
import "./App.css";
  
function App() {
    const [name, setName] = useState("");
    const [result, setResult] = useState("");
  
    const handleChange = (e) => {
        setName(e.target.value);
    };
  
    const handleSumbit = (e) => {
        e.preventDefault();
        const form = $(e.target);
        $.ajax({
            type: "POST",
            url: form.attr("action"),
            data: form.serialize(),
            success(data) {
                setResult(data);
            },
        });
    };
  
    return (
        <div className="App">
            <form
                action="http://localhost:8000/server.php"
                method="post"
                onSubmit={(event) => handleSumbit(event)}
            >
                <label htmlFor="name">Name: </label>
                <input
                    type="text"
                    id="name"
                    name="name"
                    value={name}
                    onChange={(event) => handleChange(event)}
                />
                <br />
                <button type="submit">Submit</button>
            </form>
            <h1>{result}</h1>
        </div>
    );
}
  
export default App;

Explanation of above code: Created to states (name, result), then function named handleChange() handles the change in input and at last function handleSubmit() send the form data to server and receives incoming result.

Start your PHP server inside PHP folder by going to console and change directory to PHP folder then run this command:

php -S localhost:8000

Now your PHP server is live on port 8000, now we will edit the server.php file:

server.php




<?php
    header('Access-Control-Allow-Origin: http://localhost:3000');
    $user = $_POST['name'];
    echo ("Hello from server: $user");
?>

Explanation of above code:  The header() this will allow our app running on localhost:3000 to access the data on it.

Now check your website by running command in project directory: 

npm start

Then check your website at localhost:3000 on your browser, then type your name in the input field you will get your response from server.

Output: Now go to the browser window and type URL http://localhost:3000/

Output on submitting the form

Enter a name and submit you will receive a message from the server with the input name


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!