Battle_Slug Battle_Slug - 2 years ago 72
Ajax Question

React way to use forms in html, submit action happens along with ajax request

My usecase is of following.
I have some React component looking like that:

var MyComponent = React.createClass({
handleButton() {
$.ajax..... post {this.state.inputData} to server
error: console.log(url,error)

handleInputOnChange(event) {

render: function () {
return (
<input type="text" id="input1" onChange={this.handleInputOnChange}/>

The problem is that when I push the button, the server gets the correct data, no errors in logs and everything seemingly goes fine, but the browser console shows an error:
error, ""
, strange stuff appears in the address line looking like
and the page reloads from the server, loosing all entered data.

action happens along with
request though the
doesn't contain any url or other directions to do that.
I changed
tag in the component to
tag and the problem disappeared.

But my html developer told that all input data should be handled inside the
only, and I am very wrong and so went to the dark side.

Sorry for a dumb question, I'm still a beginner in frontend, but what is the right way to handle this?

Answer Source

If you are handling the request via ajax, you should prevent the default behaviour of the button click, meaning the form won't get submitted automatically. So inside handleButton you would get the event object and call preventDefault:

handleButton(event) {
  $.ajax..... post {this.state.inputData} to server
  error: console.log(url,error)

This should stop a page refresh.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download