简体   繁体   English

使用 Ajax 在 React.js 中提交表单

[英]Submit form in React.js using Ajax

Creating my first application in React.js and want to submit contact form to a email with Ajax.在 React.js 中创建我的第一个应用程序,并希望使用 Ajax 将联系表单提交到电子邮件。 I've used this solution as guideline: https://liusashmily.wordpress.com/author/liusashmily/ but the full component file is not available, only parts and I cant reach the author.我已经使用这个解决方案作为指导: https : //liusashmily.wordpress.com/author/liusashmily/但完整的组件文件不可用,只有部分,我无法联系到作者。

Contact component接触元件

 // Create Component class Contact extends React.Component { constructor(props){ super(props); this.state = { contactEmail: '', contactMessage: '' }; this.handleSubmit = this.handleSubmit.bind(this); this.handleChange = this.handleChange.bind(this); this.handleChangeMsg = this.handleChangeMsg.bind(this); } handleChange(event) { this.setState({ contactEmail: event.target.value, }); } handleChangeMsg(event) { this.setState({ contactMessage: event.target.value }); } handleSubmit(event) { event.preventDefault(); this.setState({ type: 'info', message: 'Sending…' }); $.ajax({ url: 'php/mailer.php', type: 'POST', data: { '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) }); } render() { return ( <div className="contact"> <form className="form" onSubmit={this.handleSubmit} id="formContact"> <label>Email</label> <input id="formEmail" type="email" name="formEmail" value={this.state.contactEmail} onChange={this.handleChange} required /> <label>Meddelande</label> <textarea id="formMsg" name="formMsg" rows="8" cols="40" value={this.state.contactMessage} onChange={this.handleChangeMsg} required></textarea> <input type="submit" value="Submit" className="btn--cta" id="btn-submit" /> </form> </div> ) } }

My PHP file mailer.php我的 PHP 文件 mailer.php

 <?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["formEmail"]), FILTER_SANITIZE_EMAIL); $message = trim($_POST["formMsg"]); // Check that data was sent to the mailer. if ( 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. $recipient = "mimilundberg@icloud.com"; // Set the email subject. $subject = "New message from $email Via React Site"; // Build the email content. $email_content .= "Email: $email\\n\\n"; $email_content .= "Message: \\n$message\\n"; // Build the email headers. $email_headers = "From: <$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."; } ?>

Getting following error in console log:在控制台日志中出现以下错误:

POST http://localhost:8080/php/mailer.php 404 (Not Found) POST http://localhost:8080/php/mailer.php 404(未找到)

..and it says that error is in the "jquery-3.2.1.min.js:4" file. ..它说错误在“jquery-3.2.1.min.js:4”文件中。

I'm including jQuery script in html doc:我在 html 文档中包含了 jQuery 脚本:

 <!Doctype html> <html> <head> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title></title> <!-- <link rel="stylesheet" href="dist/styles.css"> --> <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> </head> <body> <div id="app"></div> <script src="dist/bundle.js"></script> </body> </html>

So incredibly grateful for any input!非常感谢任何输入!

I found the solution.我找到了解决方案。 Here is my Contact component:这是我的联系人组件:

import React, { Component } from 'react';

// Contact component render contact form
class Contact extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      contactEmail: '',
      contactMessage: ''
    };

    this._handleSubmit = this._handleSubmit.bind(this);
    this._handleChange = this._handleChange.bind(this);
    this._handleChangeMsg = this._handleChangeMsg.bind(this);
  }

  // Change state of input field so text is updated while typing
  _handleChange(e) {
    this.setState({
      contactEmail: e.target.value,
    });
  }
  // Change state of input field so text is updated while typing
  _handleChangeMsg(e) {
    this.setState({
      contactMessage: e.target.value
    });
  }

  _handleSubmit(e) {
    e.preventDefault();
    this.setState({
      contactEmail: '',
      contactMessage: ''
    });

    $.ajax({
      url: process.env.NODE_ENV !== "production" ? '/getMail' : "http://www.fransbernhard.se/magden/php/mailer.php",
      type: 'POST',
      data: {
        'form_email': this.state.contactEmail,
        'form_msg': this.state.contactMessage
      },
      cache: false,
      success: function(data) {
        // Success..
        this.setState({
          contactEmail: 'success',
          contactMessage: '<h1>Kontakt skickad!</h1><p>Återkommer så fort som möjligt.</p>'
        });
        $('#formContact').slideUp();
        $('#formContact').after(this.state.contactMessage);
        console.log('success', data);
      }.bind(this),
      // Fail..
      error: function(xhr, status, err) {
        console.log(xhr, status);
        console.log(err);
        this.setState({
          contactEmail: 'danger',
          contactMessage: '<h1>Sorry det blev fel</h1><p>Försök gärna igen, eller mejla mig direkt på magdamargaretha@gmail.com</p>'
        });
        console.log(this.state.contactEmail + this.state.contactMessage + 'fail');
      }.bind(this)
    });
  }

  render() {
    return (
      <div className="contact" id="contact">
        <div className="filter">
          <form className="form" onSubmit={this._handleSubmit} id="formContact">
            <label>Email</label>
            <input id="formEmail" type="email" name="formEmail" value={this.state.contactEmail} onChange={this._handleChange} required/>
            <label>Meddelande</label>
            <textarea id="formMsg" name="formMsg" rows="8" cols="40" value={this.state.contactMessage} onChange={this._handleChangeMsg} required></textarea>
            <input type="submit" value="Submit" className="btn--cta" id="btn-submit" />
          </form>
        </div>
      </div>
    )
  }
}

export default Contact;

mailer.php file: mailer.php 文件:

<?php

  // trim() function strips any white space from beginning and end of the string
  $email = filter_var(trim($_POST["form_email"]), FILTER_SANITIZE_EMAIL);
  //  strip_tags() function strips all HTML and PHP tags from a variable.
  $message = strip_tags($_POST["form_msg"]);

  // Check that data was sent to the mailer.
  if ( 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.
  $recipient = "mimilundberg@icloud.com";
  // Set the email subject.
  $subject = "Message to magdalundberg.se from: $email";

  // Build the email content.
  $body .= "Email: $email\n\n";
  $body .= "Message: \n$message\n";

  // success
  $success = mail($recipient, $subject, $body, "From:" . $email);

  // Send the email.
  if ($success) {
    // 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.";
  }

?>

As React is UI component framework you can use third party library for ajax post.由于 React 是 UI 组件框架,因此您可以使用第三方库进行 ajax 发布。 https://www.npmjs.com/package/react-axios https://www.npmjs.com/package/react-axios

Here is an example of how to use this.这是如何使用它的示例。 https://handyopinion.com/reactjs-post-form-with-ajax/ https://handyopinion.com/reactjs-post-form-with-ajax/

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

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