简体   繁体   English

我用React和PHP制作的联系表返回邮件已发送:false

[英]My contact form made with React and PHP return mailSent: false

I'm a designer, and very beginner in coding. 我是一名设计师,也是编码的初学者。 I'm creating my portfolio with React.js, and I'm trying to make a contact form using PHP. 我正在使用React.js创建我的投资组合,并试图使用PHP制作联系表格。 I'm asking the user to fill his name, email and a message. 我要用户填写他的姓名,电子邮件和消息。

I'm working on localhost:3000 (I don't if that information matters) I have 2 files : contact.js and contact_form_handler.php, both in the same directory. 我正在localhost:3000上工作(如果该信息无关紧要),我有2个文件:contact.js和contact_form_handler.php,它们都在同一目录中。 When I submit the form, I console.log the state, wich returns the informations the user filled, but the mail remains unsent. 当我提交表单时,我会console.log状态,它返回用户填写的信息,但邮件仍未发送。 Coding is new to me so maybe my question might sound stupid. 编码对我来说是新的,所以也许我的问题听起来很愚蠢。 Do I need an Apache server to run the PHP code? 我需要一个Apache服务器来运行PHP代码吗? I thought React has its own Node server. 我以为React有自己的Node服务器。

The React code: React代码:

import React, { Component } from 'react';
import axios from 'axios';

const API_PATH = 'http://localhost:3000/src/contact_form_handler.php';

class Contact extends Component {
  constructor(props) {
    super(props);
    this.state = {
      name: '',
      email: '',
      message: '',
      mailSent: false,
      error: null
    }
  }

  render() {
    return(
      <div className="contact" id="contact">
        <h2>Contact</h2>
        <div>
          <form action="/contact_form_handler.php">
          <input 
            type="text" id="name" name="name" placeholder="Votre nom"
            value={this.state.name}
            onChange={e => this.setState({ name: e.target.value })}
          />
          <input
            type="email" id="email" name="email" placeholder="Votre email"
            value={this.state.email}
            onChange={e => this.setState({ email: e.target.value })}
          />
          <textarea 
            id="message" name="message" placeholder="Votre message"
            onChange={e => this.setState({ message: e.target.value })}
            value={this.state.message}
          ></textarea>
          <input type="submit" onClick={e => this.handleFormSubmit(e)} value="ENVOYER"/>

          <div>
            {this.state.mailSent &&
              <div>Thank you for contcting us.</div>
            }
          </div>
          </form>
          </div>
      </div>
    )
  }

  handleFormSubmit( event ) {
    event.preventDefault();
    axios({
      method: 'post',
      url: `${API_PATH}`,
      headers: { 'content-type': 'application/json' },
      data: this.state
    })
      .then(result => {
        this.setState({
          mailSent: result.data.sent
        })
      })
      .catch(error => this.setState({ error: error.message }));
    console.log(this.state);
  }

}

export default Contact;

The PHP code: PHP代码:

<?php
header("Access-Control-Allow-Origin: *");
$rest_json = file_get_contents("php://input");
$_POST = json_decode($rest_json, true);

if (empty($_POST['fname']) && empty($_POST['email'])) die();

if ($_POST)
    {

    // set response code - 200 OK

    http_response_code(200);
    $subject = $_POST['name'];
    $to = "blondeau.cyril@gmail.com";
    $from = $_POST['email'];

    // data

    $message = $_POST['name'] . $_POST['message'];

    // Headers

    $headers = "MIME-Version: 1.0\r\n";
    $headers.= "Content-type: text/html; charset=UTF-8\r\n";
    $headers.= "From: <" . $from . ">";
    mail($to, $subject, $message, $headers);

    // echo json_encode( $_POST );

    echojson_encode(array(
        "sent" => true
    ));
    }
  else
    {

    // tell the user about error

    echojson_encode(["sent" => false, "message" => "Something went wrong"]);
    }

?>

Everything seems ok, but the form doesn't work, I don't receive the email when I submit the form. 一切似乎正常,但该表格无法正常工作,提交表格时我没有收到电子邮件。

Thank you for your help. 谢谢您的帮助。

Network request is async. 网络请求是异步的。 setState is also async. setState也是异步的。 You can't see immediate state change. 您看不到立即的状态变化。

If you want to actually observe modified state use a callback 如果要实际观察修改后的状态,请使用回调

  handleFormSubmit( event ) {
    event.preventDefault();
    axios({
      method: 'post',
      url: `${API_PATH}`,
      headers: { 'content-type': 'application/json' },
      data: this.state
    })
      .then(result => {
        this.setState({
          mailSent: result.data.sent
        }, () => console.log(this.state)) // NB! setState accepts callbacks
      })
      .catch(error => this.setState({ error: error.message }));

  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM