Battle_Slug Battle_Slug - 6 months ago 15
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) {
this.setState({inputData: event.target.value});
},

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


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
localhost:8080?input1=
and the page reloads from the server, loosing all entered data.

Obviously
html
submit
action happens along with
ajax
POST
request though the
<form>
doesn't contain any url or other directions to do that.
I changed
<form>
tag in the component to
<div>
tag and the problem disappeared.

But my html developer told that all input data should be handled inside the
<form>
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

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) {
  event.preventDefault()
  $.ajax..... post {this.state.inputData} to server
  error: console.log(url,error)
}

This should stop a page refresh.