Guide on integrating a php script into a react application

I'm currently in the process of setting up a functional contact form on my website by following the guidance provided in this article link. However, the tutorial includes a php script to manage the post data, and I am using create-react-app and unsure how to integrate the mailer.php file into the project.

Contact Form:

<form id="contact-form" name="c-form" method="post" action="mailer.php">
    <div className="input-field">
        <input
            id="first_name"
            type="text"
            className="validate"
            name="first_name"
            required/>
        <label for="first_name">Name</label>
    </div>
    <div className="input-field">
        <input id="sub" type="text" className="validate" name="sub"/>
        <label for="sub">Subject</label>
    </div>
    <div className="input-field">
        <input id="email" type="email" className="validate" name="email" required/>
        <label for="email">Email</label>
    </div>
    <div className="input-field">
        <textarea
            id="textarea1"
            className="materialize-textarea"
            name="message"
            required></textarea>
        <label for="textarea1">Message</label>
    </div>
    <div className="contact-send">
        <button
            id="submit"
            name="contactSubmit"
            type="submit"
            value="Submit"
            className="btn waves-effect">Send
        </button>
    </div>
</form>

PHP Mailer Script:

<?php

// Processing only POST requests.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Extracting form fields and eliminating whitespace.
    $name = strip_tags(trim($_POST["name"]));
                $name = str_replace(array("\r","\n"),array(" "," "),$name);
    $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
    $message = trim($_POST["message"]);

    // Checking if the necessary data was sent to the mailer.
    if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        // Returning a 400 (bad request) response code and exiting.
        http_response_code(400);
        echo "Oops! There was an issue with your submission. Please fill out the form and try again.";
        exit;
    }

    // Setting the recipient email address.
    // FIXME: Update this to your preferred email address.
    $recipient = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4b213b24393f2439392e2a277c7c0b2c262a222765282426">[email protected]</a>";

    // Setting the email subject.
    $subject = "New contact from $name";

    // Creating the email content.
    $email_content = "Name: $name\n";
    $email_content .= "Email: $email\n\n";
    $email_content .= "Message:\n$message\n";

    // Creating the email headers.
    $email_headers = "From: $name <$email>";

    // Sending the email.
    if (mail($recipient, $subject, $email_content, $email_headers)) {
        // Setting a 200 (ok) response code.
        http_response_code(200);
        echo "Thank You! Your message has been sent.";
    } else {
        // Setting a 500 (internal server error) response code.
        http_response_code(500);
        echo "Oops! Something went wrong and we couldn't send your message.";
    }

} else {
    // If not a POST request, set a 403 (forbidden) response code.
    http_response_code(403);
    echo "There was a problem with your submission, please try again.";
}

?>

ReactJS Component:

componentDidMount() {

var $form = $("#contact-form");
var formData = $form.serialize();

$form.submit(function (event) {
    // Preventing the browser from submitting the form.
    event.preventDefault();

    // TODO
    $.ajax({
        type: 'POST',
        url: $form.attr('action'),
        data: formData,
        success: function (response) {
            console.dir(response);
        },
        fail: function (err) {
            console.dir(err);
        }
    });

});

}

Issue:

Upon submitting the form, I encounter a

POST http://localhost:3000/mailer.php 404 (Not Found)

error. How can I resolve this and get it functioning properly?

Answer №1

create-react-app is a fantastic tool that allows developers to easily set up a front-end application without much hassle. However, it does not come with php support.

Here's how you can integrate php into your create-react-app project:

  1. First, make sure you have a php server up and running. If you need guidance on this, check out this tutorial. Let's assume your php page is working at .

  2. Once you've confirmed that is functioning properly, start sending data asynchronously.

Answer №2

When facing a 404 status page error on my local host ( http://localhost:3000/post), I found a solution by accessing my website through the host domain address. Here are two possible methods to try:

"proxy":"http://localhost:80"

You can use Wamap, Xamp or any other platform with an Apache server for PHP running on Port 80. Additionally, you may need to include some code in your Php file for CROS.

In another approach similar to using functions.php in WordPress, you can create a JavaScript file to establish a connection between React and PHP since direct insertion of PHP code in React files is not supported. Ensure that both servers (React Node and Apache) are running simultaneously. It's recommended to set up a Virtual Host on Apache with proper permissions. An htaccess file should also be created containing:

Options -MultiViews
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]

Separate folders for PHP and React applications should be maintained, with the .htaccess file placed in the PHP folder. These guidelines should assist you in addressing the issue effectively. Best of luck!

Answer №3

When utilizing React in conjunction with PHP, the recommended approach involves creating two separate directories within the project folder - one for the application's frontend and the other for backend functionality handled by PHP. For a detailed look at the code implementation, visit my profile on the academic platform: . The instructional content is presented in Serbian language; however, you can easily interpret the code snippets provided. Initial steps include establishing the necessary folders and configuring a proxy to facilitate seamless data transfer over port 80 where PHP operates in response to frontend requests specified in package.json. Following this setup, .htaccess file must be configured within the PHP directory to enable proper routing based on the instructions outlined in the linked documentation. It is crucial to adapt field names and any other variables as needed within your own implementation. In essence, JSON data is parsed and decoded accordingly to extract relevant information passed between the frontend React application and the server, in adherence to standard data transmission protocols.

Answer №4

One way to integrate APIs with your React Project is by setting up a back-end server, hosting it like you would a PHP project, and then utilizing the endpoints within your application.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to display the Breadcrumb with the recursive function in PHP

Seeking assistance on implementing a recursive function method in PHP to display breadcrumbs. Here's the code I currently have: function getCategoryTreeIDs($qs_type_id) { $crumbsql = "SELECT parent_id FROM lists WHERE id=$qs_type_id"; ...

Accessing files from SharePoint using web services and jQuery

I am in the process of creating a mobile application that will connect to a MOSS Site through web services. The main functionalities I aim to achieve are: 1) Retrieve documents such as PDFs, Word documents, Excel files. 2) Access reporting services report ...

Trouble with Bootstrap 3's nav-justified feature not displaying correctly upon window expansion

Looking at this Bootstrap example page, I noticed a small issue with the nav-justified navigation. When the window is minimized, it transitions correctly to a mobile version. However, when the window is maximized again, the buttons remain in the mobile for ...

Tips for determining the width of an image and utilizing that measurement as the height in order to create a balanced square image

I am currently facing an issue with my code that is used to retrieve the width of an image which is set in percentages. Although I am able to obtain the width in pixels, I am struggling with correctly inserting the variable into the CSS property value usin ...

"Encountered a 'Network Error' while using Axios and DjangoREST, but pleasantly surprised when the request ultimately succeeds

So, I'm currently using ReactJS and DjangoRESTframework for my app development. When I test the API endpoints with Postman, everything works perfectly (e.g. 127.0.0.1:8000/api/users/ GET request). However, when I try to make the same requests in Rea ...

Displaying merged rows with shared field

With a vast database filled with our products, each having multiple variants, the table structure appears as follows: id | Name | VariantName | dim1 1 | ProductA | Option1 | 120 2 | ProductA | Option2 | 160 3 | ProductA | O ...

Issue with the format of incoming data in Ajax post request when working with Django framework

Hello everyone, I am currently working on a script to send a post request to my Django backend. My goal is to have the data in Json format. <input id ="my" type="submit" onclick="me()"/> <script> function me() { var data2 =JSON.stringif ...

Components in array not displaying in React

I've been struggling to generate a table from an array in React. Typically, I retrieve data from a database, but for testing purposes, I manually created the array to ensure the data is correct. Despite following examples by enclosing my map code with ...

Verifying Username with AJAX and JSON Technology

In a PHP file, I have stored usernames in JSON format. [ {"korisnicko_ime":"darbranis"}, {"korisnicko_ime":"markrc"}, {"korisnicko_ime":"leoluk"}, {"korisnicko_ime":"borbau"}, {"korisnicko_ime":"ivavad"}, {"korisnicko_ime":"andtikv ...

One Page HTML5 with a Bootstrap fixed top menu, revealing content on menu item click

Is there a way to have the Bootsrap mobile menu automatically unfold when a link (anchor on the same page) is clicked? The menu unfolds with class navbar-collapse collapse in The menu folds with class navbar-collapse collapse out I already have an oncl ...

Updating Page Content with JQuery AJAX Post Without Page Reload

So I realize I may be asking a question that has been asked before, but as a complete beginner with AJAX jQuery, I'm not sure what to search for. I've tried searching without success, so please bear with me. I have a PHP WordPress site that defa ...

Displaying JSON data after a successful AJAX call

I am currently facing an issue with my controller. I have a query that returns data in JSON format, and I'm trying to display this data in the view using AJAX and jQuery. However, every time I try to output the data, it shows as [object Object]. I sus ...

Social media comments widget

Currently, I am incorporating the Facebook XML to implement a Facebook comments plugin within my MVC 3 application in the following manner: <fb:comments href="@Request.Url.AbsoluteUri" num_posts="15" width="900"></fb:comments> The issue lies ...

Creating a QR code alongside an image positioned in the center: Step-by-step guide

Is there a way to create a QR code using react js or node js? I'm looking for a library or package that can generate a QR code with an image in the center. Do you know of any options? For example: ...

formik does not support using the "new Date" function as an initial value

I have been trying to set the initial value of a date in my component like this, but when it renders I am encountering an error. const formik = useFormik ({ initialValues: { dob: new Date () } }) During this process, I'm facing the follow ...

Utilizing TypeScript/React to Access Data from an Excel Spreadsheet

Hey there! I've been working on a Single-Page-Application with Typescript and React, and now I need to read data from an Excel sheet. The xlsx Library (npm) seems to be the way to go, but I'm having trouble getting it to work. Can anyone offer an ...

Guide to deploying a React application - paths requiring adjustments

I am a novice developer looking to learn more. Recently, I decided to clone Emilio Quintanas Servitodo APP into my own repository. After downloading the repo, I attempted to use gh-pages with npm to build and deploy the APP. However, I encountered an issue ...

Enter the width and height of the image you want to insert using PHP

Is there a way to specify the width as 200px and let the height adjust automatically in this code? echo '<img src="'.$image_name .'" alt="'.$image_name.'"/> '."<br /><br />"; } ...

What could be causing React to generate an error when attempting to utilize my custom hook to retrieve data from Firebase using context?

Currently, I am restructuring my code to improve organization by moving data fetching to custom hooks instead of within the component file. However, I am encountering issues with the hook not functioning properly when used in conjunction with my context. ...

What is the best approach to manage the Start Event for SlideToggle?

Currently, I am reviewing the documentation for slidetoggle and came across an event for start event: http://api.jquery.com/slidetoggle/, however, I am unsure of how to utilize this. Any guidance on how to use it would be greatly helpful! Thank you in adv ...