I am trying to send HTML form data as a JSON to java rest api and it generates response as JSON. Here is my code.
HTML FORM:
<html>
<body>
<form action ="" method= "post" name= "testform">
<p> Balance : <input type="text" id="balance" name="balance" /></p>
<p>Pin : <input type="text" id="pin" name="pin" /></p>
<p>CardID : <input type="text" id="cardId" name="cardId" /></p>
<input type ="submit" id="add-account" value="add user"></input>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="js/main.js"></script>
</body>
</html>
Jquery CODE:
$(function(){
console.log("Jquery called");
$('#add-account').click(function(event){
event.preventDefault();
var balance = $("#balance").val();
var pin = $("#pin").val();
var cardId = $("#cardId").val();
var firstcall =
$.ajax({
type: "POST",
url: "http://localhost:8081/quickpay/webapi/myresource",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({
"balance":balance,
"pin": pin,
"cardId": cardId
}),
dataType: "json",
success:function (successResponse,textStatus,jqXHR) {
alert("first api");
},
error: function (errorResponse1) {
console.log(errorResponse1);
alert("failed first api");
}
});
});
});
JAVA REST API:
@Path("myresource")
public class MyResource {
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Account createAccount(Account acc){
Account account = AccountService.createAccount(acc.getBalance(),acc.getPin(),acc.getCardId());
return account;
}
}
OUTPUT I'm getting is:
When I try to call the api in POSTMAN, it runs successfully and data is inserted successfully. When I try to click on ADD USER button , data is inserted into database successfully but ALERT messege of success function does not appear.
I'm monitoring network tab of Google chrome, There I find this error in myresource status is cancelled and type is xhr.
When hovering mouse on Jquery.min.js I get this..
n.ajaxTransport.k.cors.a.crossDomain.send @ jquery.min.js:4
n.extend.ajax @ jquery.min.js:4
(anonymous function) @ main.js:9
n.event.dispatch @ jquery.min.js:3
n.event.add.r.handle @ jquery.min.js:3
Problem : How can I make success function of ajax call working ?? Where I'm going wrong.?
EDIT: I added preventDefault() method. So Now It is working!
答案 0 :(得分:2)
You do not cancel the button click so the form submits
$('#add-account').click(function(e){
e.preventDefaul();
...