How to connect ReactJS as a front-end with PHP as a back-end ?
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.
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:
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.
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:
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:
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/
Enter a name and submit you will receive a message from the server with the input name
Please Login to comment...