Submit form in React.js using Ajax

前端 未结 2 521
猫巷女王i
猫巷女王i 2021-02-10 01:08

Creating my first application in React.js and want to submit contact form to a email with Ajax. I\'ve used this solution as guideline: https://liusashmily.wordpress.com/author/l

2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-10 01:37

    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: '

    Kontakt skickad!

    Återkommer så fort som möjligt.

    ' }); $('#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: '

    Sorry det blev fel

    Försök gärna igen, eller mejla mig direkt på magdamargaretha@gmail.com

    ' }); console.log(this.state.contactEmail + this.state.contactMessage + 'fail'); }.bind(this) }); } render() { return (
    ) } } export default Contact;

    mailer.php file:

    
    

提交回复
热议问题