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