React.js how to I go about getting data from my form and posting it React.js how to I go about getting data from my form and posting it reactjs reactjs

React.js how to I go about getting data from my form and posting it


As @BinaryMuse noted the problem here is that your submit method is not really doing any submitting. You mentioned that the way you want to do this is via AJAX, and thus you need to 1) include jQuery (or Zepto) on your page, and 2) make the ajax call. Here is one way to accomplish the second part:

1) First, you don't really need to provide the submit method as a property to the submit button. When the submit button is clicked inside a form, it will trigger the form's onSubmit event, so you can simply attach the this.submit method there.

Also, you don't really need I don't think to create a separate component for the Submit button. That kind of granularity may not be justified here since you can accomplish the same thing with far fewer lines of code. So I'd remove your SubmitButton component and update your Contact component render function to be:

    render: function(){       return (        <form onSubmit={this.submit}>          <BasicInputBox label="Name:" valChange={this.nameChange} val={this.state.name}/>          <BasicInputBox label="Email:" valChange={this.emailChange} val={this.state.email}/>          <CommentBox valChange={this.commentChange} val={this.state.comment}/>          <button type="submit">Submit</button>        </form>      );    }

2) Next you can change your submit method in this way, adding an AJAX call. Depending on the details of the server/API to which you are sending the form you may need to modify the AJAX call a bit, but what I have put here is a fairly generic form that has a good chance of working:

submit: function (e){  var self  e.preventDefault()  self = this  console.log(this.state);  var data = {    name: this.state.name,    email: this.state.email,    comment: this.state.comment  }  // Submit form via jQuery/AJAX  $.ajax({    type: 'POST',    url: '/some/url',    data: data  })  .done(function(data) {    self.clearForm()  })  .fail(function(jqXhr) {    console.log('failed to register');  });}

Note: that I also encapsulated the code you had previously for clearing the form inside its own function, which is called if the AJAX call returns a success.

I hope this helps. I put the code in a jsFiddle where you could test it a bit: https://jsfiddle.net/69z2wepo/9888/