Reputation: 82
I'm trying to set up a local server that hosts a comment submission system (as per the React tutorial). In the CommentForm
class, I want to have the form handle a comment submission, which uses a POST request to modify a local file called comments.json. This POST request isn't working. Can anyone figure out why? I have the following code (I have excluded the Comment and CommentList classes to reduce clutter but I will include them if it will be helpful). The console.log line that prints "submitting" is never executed:
var Comment = React.createClass({
// code excluded for brevity
});
var CommentForm = React.createClass({
handleSubmit: function(e) {
console.log("submitting");
e.preventDefault();
var author = this.refs.author.value.trim();
var text = this.refs.text.value.trim();
if (!text || !author) {
return;
}
this.props.onCommentSubmit({author: author, text: text});
this.refs.author.value = '';
this.refs.text.value = '';
return;
},
render: function() {
return (
<form className = "commentForm">
<input type="text" placeholder="Your name" ref="author"/>
<input type="text" placeholder="Say something..." ref="text"/>
<input type="submit" value="Post"/>
</form>
);
}
});
var CommentList = React.createClass({
// code excluded for brevity
});
var CommentBox = React.createClass({
loadCommentsFromServer: function() {
$.ajax({
url: this.props.url,
dataType: 'json',
cache: false,
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
getInitialState: function() {
return {data: []};
},
handleCommentSubmit: function(comment) {
$.ajax({
url: this.props.url,
dataType: 'json',
type: 'POST',
data: comment,
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
componentDidMount: function() {
this.loadCommentsFromServer();
setInterval(this.loadCommentsFromServer, this.props.pollInterval);
},
render: function() {
console.log("rendering box");
return (
<div className="commentBox">
<h1>Comments</h1>
<CommentList data={this.state.data} />
<CommentForm onCommentSubmit={this.handleCommentSubmit} />
</div>
);
}
});
ReactDOM.render(
<CommentBox url="/api/comments" pollInterval = {2000} />,
document.getElementById('content')
);
Upvotes: 0
Views: 274
Reputation: 14907
You forgot to bind the onSubmit
event of the form the handler.
<form className="commentForm" onSubmit={this.handleSubmit}>
Upvotes: 1