Sending Email by using Ajax in an React Contact Form

I have been working on an React site for a while, and I was so happy to finally figure out how to send an email by using ajax on this site. Thought I’d write it down for future/other references. Please let me know if you have any questions or suggestions.

Here is the interface for the contact form.

screen-shot-2017-01-10-at-12-06-23-pmHere is the basic setup:
Server: Apache + PHP + MySQL (the database is not important here. I am listing the PHP server because I used the mail function in my mailer.php)
mailer.php: Get the data about the email, sanitize it and send the email.
Contact.js: The React Contact form. It also sends the data through an ajax request to the mailer.php.

Here is the code for the form:

<form id=”contactForm” method=”POST” action=”mailer.php” onSubmit={this.handleSubmit}>
<fieldset className=”form-group”>
<label for=”form_name”>Name</label>
<input type=”text” value={this.state.contactName} className=”form-control” id=”form_name” onChange={this.handleNameChange} />
</fieldset>

<fieldset className=”form-group”>
<label for=”form_email”>E-mail:</label>
<input value={this.state.contactEmail} className=”form-control” id=”form_email” type=”email” onChange={this.handleEmailChange} />
</fieldset>

<fieldset className=”form-group”>
<label for=”form_msg”>Message:</label>
<textarea value={this.state.contactMessage} className=”form-control” id=”form_msg” onChange={this.handleMessageChange} ></textarea>
</fieldset>

</form>

Here are the code in mailer.php:

if ($_SERVER[“REQUEST_METHOD”] == “POST”) {

$name = strip_tags(trim($_POST[“form_name”]));
$name = str_replace(array(“\r”,”\n”),array(” “,” “),$name);
$email = filter_var(trim($_POST[“form_email”]), FILTER_SANITIZE_EMAIL);
$message = trim($_POST[“form_msg”]);

// Check that data was sent to the mailer.
if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
http_response_code(400);
echo “Oops! There was a problem with your submission. Please complete the form        and try again.”;
exit;
}

// Set the recipient email address.
// FIXME: Update this to your desired email address.
$recipient = “example@example.com”;

// Set the email subject.
$subject = “New contact from $name Via React Site”;

// Build the email content.
$email_content = “Name: $name\n”;
$email_content .= “Email: $email\n\n”;
$email_content .= “Message:\n$message\n”;

// Build the email headers.
$email_headers = “From: $name <$email>”;

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

} else {
// 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.”;
}

As you may have already noticed that in the React form Contact.js, there are only three piece of information we need to send, including the sender’s name, email address and message content. When the user click the “Send your message” button, it will trigger the “handleSubmit()” function, which contains the ajax request. Here is the code in the handleSubmit() function.

handleSubmit(event) {

event.preventDefault();
this.setState({ type: ‘info’, message: ‘Sending…’ });

$.ajax({

url: ‘/…./mailer.php’,
type: ‘POST’,
data: {

“form_name”: this.state.contactName,
“form_email”: this.state.contactEmail,
“form_msg”: this.state.contactMessage

},
cache: false,
success: function(data) {

// Success..
this.setState({ type: ‘success’, message: ‘We have received your message and will get in touch shortly. Thanks!’ });

}.bind(this),

error: function(xhr, status, err) {
this.setState({ type: ‘danger’, message: ‘Sorry, there has been an error.  Please try again later or visit us at SZB 438.’ });
}.bind(this)

});

}

18 thoughts on “Sending Email by using Ajax in an React Contact Form

  1. Thanks for posting! Can you post the code for the form? Did you use controlled or uncontrolled inputs for the form? Thanks.

      1. Thanks for the follow up! I ended up using Axios, to avoid having to use JQuery.

        I also wanted to point out, it looks like you’re not using the response data that’s returned from mailer.php. You should be able to use the data returned from your success and error functions as your response rather than hard coding the responses. I point it out because having the response codes in the PHP file and then having the Contact.js file set a hardcoded value had me confused and it might help the next person looking at your code.

        Example:

        `// Success..
        this.setState({ type: ‘success’, message: ‘We have received your message and will get in touch shortly. Thanks!’ });`

        Using mailer.php response data:

        `// Success..
        // mailer.php was returning an object so I needed to specify the message property of the object
        let response = data.message;
        this.setState({ type: ‘success’, message: response });`

        Thanks again!

  2. Hi liusashmily,
    Is it possible to send the mail without php? My website is only react (running on aws S3).

      1. Thank you for the reply liusashmily,
        I have found a way to do it. I’ll be using AWS SES (simple email service) via API Gateway.
        have a great day!

  3. Great Post! I keep getting a 404 for my index.php file for some reason. I have the index.php file in the same folder as my Contact.js component. How did you organize your files to make this work?

    1. Hey, did you draw the form in the index.php? You might want to change the path in the code. I did “url: ‘/…./mailer.php’”. You can probably just use “url: “mailer.php’,”

      1. The form is in my Contact.js component. And the index.php file is in the same folder as my Contact.js component (with the hopes of limiting path conflict as much as possible) but I’ve tried index.php, /index.php, ./index.php, components/index.php, etc. I can’t seem to get the request to find the file. Where is your mailer.php in relation to your contact component? I was thinking of putting it in my public folder. Or do I have to import the index.php file the way I import other components?

  4. hey, matt, what were you trying to accomplish in the index.php? were you trying to make contact.js to find the index.php file? why would you import the index.php file?

    i believed mine was in the folder. I am sorry it has been so long, and I am no longer have access to these files. Good luck!!

  5. Hey, This is exactly what I was looking for this afternoon and the comments are helpful. I haven’t used PHP before this is perfect for a beginner like me. Incorporating it now into my site.

  6. Receive thousands of people who are ready to buy delivered to your website for the low price of only $38. Would you be interested in how this works? Simply reply to this email address for more information: isla7996gre@gmail.com

Leave a reply to Patrick Cancel reply