Reputation: 116
First of all I am new to React so if there's something to improve tell me.
I have a login form that sends the information with ajax to php,I want to catch the error and update a p element althought i cannot find the way to do it.
When it's wrong the message that I send with php i want to call another method however it says undefined.
var APP = React.createClass({
getInitialState:function(){
return{user:'',pass:'',message:''};
},
setUser:function(e){
this.setState({user:e.target.value});
},
setPass:function(e){
this.setState({pass:e.target.value});
},
setErrors:function(errors){
alert('calling');
this.setState({message:errors});
},
handleForm:function(e){
e.preventDefault();
var username = this.state.user;
var password = this.state.pass;
$.ajax({
'url':'prg/loginJSON.php',
'type':'POST',
data:{'username':username,'password':password},
success:function(result){
if(result.error){
window.location.href="http://localhost/learnSeries/home.html";
sessionStorage.setItem('cookiePass',result.token);
}
else{
this.setErrors(result.message);
}
},
error:function(xhr){
console.log('error ajax' +xhr.responseText);
}
});
},
render:function(){
return(
<form onSubmit={this.handleForm} id="loginForm" method="post" action="" role="form">
<label className="is-required">User</label>
<input type="text" name="username" onChange={this.setUser} id="username" required placeholder="User"></input>
<label className="is-required">Password</label>
<input type="password" name="password" onChange={this.setPass} id="password" required placeholder="Password"></input>
<input type="submit" value="Log In"></input>
<p>{this.state.message}</p>
</form>
)
}
});
React.render(<APP />, document.getElementById('site'));
Upvotes: 0
Views: 263
Reputation: 1191
The this
in the success
function is not the same as when you started the request with $.ajax
. You have to remember it and use it instead of this
later on (in my
handleForm:function(e){
// ...
// -->
var self = this;
// <--
$.ajax({
// ...
success:function(result){
if(result.error){
// ...
}
else{
// -->
self.setErrors(result.message);
// <--
}
},
// ...
});
Upvotes: 1