Reputation: 2351
I am trying to call a rest api from my login page on click of a button. I am using $.ajax to do so. The POST request gets sent and 200 code is also showing on backend. But in my browser network tab it shows failed. I don't know what is wrong. I am trying to print the response in the console when response comes from api, but nothing get printed. That means api is getting the POST req, it is generating a token for me and sending it to me but my client side is failing to get the response. Here is my code and essential screenshots. P.S. I don't get any error in console.
import React, {Component} from 'react'
import {Router, Route, browserHistory, IndexRoute} from "react-router"
require("./login.css")
import valueLink from 'valuelink'
import $ from 'jquery'
export default class LogInComponent extends Component {
handleLoginButtonClick() {
var settings = {
"async": true,
"crossDomain": true,
"url": "https://******appspot.com/auth/login/",
"method": "POST",
"credentials": 'include',
"headers": {
"content-type": "application/x-www-form-urlencoded",
},
"data": {
"password": "****",
"username": "****"
}
}
$.ajax(settings).done(function () {
alert("success");
});
}
render(){
return (
<div className="LoginPage">
<div className="login-page">
<div className="form">
<form className="login-form">
<input id="username" type="username" placeholder="username"/>
<input id="password" type="password" placeholder="password"/>
<button onClick={this.handleLoginButtonClick}>login</button>
<p className="message">Not registered? <a href="#">Request Username and Password</a></p>
</form>
</div>
</div>
</div>
);
}
}
This is my network tab
This is when I click :3000... from initiator column. The highlighted line is where it takes me.
Upvotes: 0
Views: 69
Reputation: 5674
Your button submits the form when clicked because the default type for the button element is submit
. This happens even when you give it your own click handler. The form submit basically just reloads your page since the form lacks the action
-attribute, so it reloads during your ajax request, which cancels it (as you can see from your network tab). You have several ways to solve this.
You can add type="button"
to the button element:
<button type="button" onClick={this.handleLoginButtonClick}>login</button>
You can cancel the default native event handling in the onClick handler:
handleLoginButtonClick(event) {
event.preventDefault();
...
}
You can use an onSubmit handler on the form element, instead of an onClick handler on the button:
<form className="login-form" onSubmit={this.handleLoginFormSubmit}>
...
</form>
with
handleLoginFormSubmit(event){
event.preventDefault(); // Stop form from submitting
...
}
Upvotes: 1