Saturday, December 28, 2024
Google search engine
HomeLanguagesHow to connect ReactJS as a front-end with PHP as a back-end...

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

Connecting the front end of React with the PHP backend is a classic approach to building a web application with the front end for the user interface and the back end or server side for handling databases, programming logic, and other operations.

React JS

React JS 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.

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

The project strucuture will look like this.

Example: Create a form in app.js with name input field and submit button linked to the php server and a result component to render output.

App.js




// Filename - 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 handleSubmit = (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) => handleSubmit(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;


Step 4: 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:

Here, the header() this will allow our app running on localhost:3000 to access the data on it.

PHP




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


Steps to run the application: Now check your website by running command in project directory: 

npm start

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

Output on submitting the form

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments