Search code examples
phpreactjsformsaxiosphpmailer

How to submit a form in ReactJs to a PHP handler (PHP miler to email form data) with Axios?


I have written a basic form in ReactJs. I am preventing the default submission as I want to do some checks before the form is submitted. Let us say the form is successfully submitted, then I want the server to gather the data and then send it as an email to an address. The data that has to be sent is just very basic formatting. So till the form submission everything works but in the console I see an error Failed to load resource: the server responded with a status of 500 (). I just intend to send this data as an email via PHP mailer.

So I checked online for a few solutions. I ended up using FormData() API in JavaScript along with headers: {'Content-Type': 'multipart/form-data' } parameter with AxiosJs to make the AJAX request. This is basically via some StackOverflow research that I have come to this point. I can see in the Network tab in DevTools that the data is being sent. I know not much about Php, so I am assuming that the fault has to be somewhere with the code that I procured online and have since tried to manipulate.

Reactform.jsx

import React, { Component } from 'react';
import {sendData} from './../../axios/getData';

export default class GameOver extends Component {

    constructor(props){
        super(props);
        this.state = {
            ...
        }
    }

    handleChange = (event) => {
        const target = event.target;
        const value = target.value;
        const name = target.name;
        this.setState({
            [name]: value
        })
    }

    handleSubmit = (event) => {
        event.preventDefault();
        const self = this;
        if (this.state.codeCheck === this.state.code){
            sendData(self.state)
            .then(()=>{self.setState({formSuccess: true})})
            .catch(()=>{self.setState({formSuccess: false})});

        } else {
            self.setState({formSuccess: false});
            alert('The secret code is incorrect. Please contact your mentor or teacher.')
        }
    }
    render() {
        return (
            this.props.gameOver &&
            <div className="success slideInRight">
                    <Gameover />
                            <div>
                                <form className = "success-form" onSubmit = {this.handleSubmit}>
                                    <label>
                                        Uw Naam:
                                        <input type="text" name="name" placeholder = "John Doe" value = {this.state.name} onChange = {this.handleChange} required />
                                    </label>
                                    <label>
                                        Uw email:
                                        <input type="email" name="email" placeholder = "[email protected]" value = {this.state.email} onChange = {this.handleChange} required />
                                    </label>
                                    <label>
                                        Uw score:
                                        <input type="number" name="score" value = {this.state.score} readOnly />
                                    </label>
                                    <label>
                                        Rubriek:
                                        <input type="text" name="genre" value = {this.state.genreName} readOnly />
                                    </label>
                                    <label>
                                        Uw School:
                                        <input type="text" name="school" placeholder =  "Enter your school name" onChange = {this.handleChange} required />
                                    </label>
                                    <label>
                                        Uw groep:
                                        <input type="text" name="group" placeholder = "Enter your group name" onChange = {this.handleChange} required />
                                    </label>
                                    <label>
                                        Uw code:
                                        <input type="text" name="code" placeholder =  "Enter your secret code" onChange = {this.handleChange} required />
                                    </label>
                                    <input type="submit" value="Submit" />
                                </form>
                            </div>
                        </div>
                        <button onClick = {()=>{ this.props.resetGame()} }>Restart Game</button>
                    </div>
            </div>
        )
    }
}

Axios.js

function sendData(data){
    const formData = new FormData();
    formData.set('name', `${data.name}`);
    formData.set('email', `${data.email}`);
    formData.set('score', `${data.score}`);
    formData.set('group', `${data.group}`);
    formData.set('school', `${data.school}`);
    formData.set('genre', `${data.genreName}`);



    return axios({
        method: 'post',
        url: `${process.env.REACT_APP_POST_URL}`,
        data: formData,
        headers: {'Content-Type': 'multipart/form-data' }
    }).then((data)=>{
        console.log(data);
    })

}

emailData.php

<?php
if(isset($_POST['email'])) {
    PRINT($_POST);
    // EDIT THE 2 LINES BELOW AS REQUIRED
    $email_to = "[email protected]";
    $email_subject = "A new score submission";
 
        
 
    $name = $_POST['name']; 
    $email_from = $_POST['email']; 
    $score = $_POST['score'];
    $genre = $_POST['genre'];
    $school = $_POST['school'];
    $group = $_POST['group'];
 
    
 
    $email_message = "Game Submission details below.\n\n";
 
     
    function clean_string($string) {
      $bad = array("content-type","bcc:","to:","cc:","href");
      return str_replace($bad,"",$string);
    }
 
     
 
    $email_message .= "Name: ".clean_string($name)."\n";
    $email_message .= "Email: ".clean_string($email_from)."\n";
    $email_message .= "Score: ".clean_string($score)."\n";
    $email_message .= "Genre: ".clean_string($genre)."\n";
    $email_message .= "School: ".clean_string($school)."\n";
    $email_message .= "Group: ".clean_string($group)."\n";
 
// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
@mail($email_to, $email_subject, $email_message, $headers);  
 
} else {
    print("Error in data")
}
?>

So this is the code I am busy with now.

  1. I submit the form and see the data in the network tab of dev tools

  2. I get an error Failed to load resource: the server responded with a status of 500 ()

  3. And there is no sending of the email.

Thanks in advance for helping me out here.


Solution

  • A 500 response code is a server error, so your request did reach the server but it couldn't handle it. You need to be looking at the server(php) logs.