spring Rest call through ajax - ajax

I am stuck with a problem when i send POST request through ajax to Spring Rest i am getting following error. But it is working fine with Postman tool.
How to solve this? Please help.
#RestController
public class LoginController {
#Autowired
LoginServiceBo loginServiceBo;
public void setLoginServiceBo(LoginServiceBo loginServiceBo) {
this.loginServiceBo = loginServiceBo;
}
#RequestMapping(value="/login",method = RequestMethod.GET)
public ModelAndView redirectLoginForm() {
System.out.println("Login Page...");
return new ModelAndView("login");
}
#RequestMapping(value="/login",method=RequestMethod.POST, consumes=MediaType.APPLICATION_JSON_VALUE, produces=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Login> login(#RequestBody Login login) {
System.out.println("Checking Login Credentials...");
boolean isValid=loginServiceBo.checkUserLogin(login);
if(isValid) {
System.out.println("Found...");
return new ResponseEntity<Login>(login, HttpStatus.ACCEPTED);
}
System.out.println("Not Found...");
return new ResponseEntity<>(login, HttpStatus.NOT_FOUND);
}
}
In javascript
function RestPost() {
userId = document.getElementById("userId");
password = document.getElementById("password");
var json = {
"userId": userId,
"password": password
};
$.ajax({
url: prefix + "/login",
type: 'POST',
data: JSON.stringify(json),
cache: false,
dataType: 'json',
beforeSend: function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
success: function(response) {
alert(JSON.stringify(response));
},
error: function(jqXhr, textStatus, errorThrown) {
alert(jqXhr.status + ' ' + jqXhr.responseText);
}
});
}

Related

send complex and simple parameter to web api using ajax

i write web api.
web api controller:
public class TaskApiController : ApiController
{
[HttpPost]
public IHttpActionResult PostNewTask(string xx,string yy,CommonTask Task)
{
...
}
}
and ajax:
var task = new Object();
task.Description = 'kjk';
task.ID = null;
var req = $.ajax({
url: 'http://localhost:3641/api/TaskApi',
contentType: "application/json",
data: {"xx":'admin',"yy":'123',"task": JSON.stringify(task) },
type: 'Post',
success: function (data) {
alert('success');
}
});
req.fail(function (jqXHR, textStatus) {
alert("Request failed: " + jqXHR.responseText);
});
and WebApiConfig:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
when run ajax, return error:
No action was found on the controller 'TaskApi' that matches the request
Always feed the POST methods with class type parameters. Please do the following modification on the API and JavaScript.
1. Create a model class
<pre>
public class Model
{
public string xx { get; set; }
public string yy { get; set; }
public CommonTask Task { get; set; }
}
</pre>
Then modify your Web API to accept a type of your class model
<pre>
public class TaskApiController : ApiController
{
[HttpPost]
public IHttpActionResult PostNewTask([FromBody] Model model)
{
}
}
</pre>
Change your ajax method to pass a json object similar to the Model class
<pre>
var task = new Object();
task.Description = 'kjk';
task.ID = null;
var data = {
"xx": 'admin',
"yy": '123',
"task" : JSON.stringify(task)
};
var req = $.ajax({
url: 'http://localhost:3641/api/TaskApi',
contentType: "application/json",
data: {"model": JSON.stringify(data) },
type: 'Post',
success: function (message) {
alert('success');
}
});
req.fail(function (jqXHR, textStatus) {
alert("Request failed: " + jqXHR.responseText);
});
</pre>

MissingServletRequestParameterException : Required Long parameter prod_id is not present

When I make a post request from Postman it works fine,but from ajax it gives the below error.Please help.Thanks in advance
Server side
#PostMapping(value = "/delete")
public ResponseEntity<BaseResponse> delete(#RequestParam("prod_id") Long productId) throws URISyntaxException {
BaseResponse response = new BaseResponse();
try{
productRepository.deleteById(productId);
response.setStatus(MessageType.SUCCESS);
}catch (Exception e){
response.setStatus(MessageType.FAIL);
}
return ResponseEntity.ok(response);
}
Ajax request
$(document).on('click','.delIcon',function(){
var row1 = $(this).closest('tr');
row = row1;
var data = $('#datatable').dataTable().fnGetData(row1);
var productId = data[0];
$.ajax({
url: "delete",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: {"prod_id": productId },
success: function(response) {
if(response.status == 'SUCCESS' ){
alert('Deleted Successfully');
}
},
error: function(xhr) {
alert("Delete response got");
}
});
});
The problem has solved after removing contentType: "application/json; charset=utf-8" as #Postmapping accept only "application/x-www-form-urlencoded".So If I define contentType then it works fine

Error 415 with ajax request (Spring)

My ajax request gets sent but never reaches my conrtroller, I get a 415 Error ()
The Ajax Request
function likeAjax(mId) {
var data = {}
data["id"] = mId;
$.ajax({
type : "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
url : "/likeMessage",
data : JSON.stringify(data),
dataType : 'json',
timeout : 100000,
beforeSend :(xhr)=>{
xhr.setRequestHeader(csrfheader,csrftoken); //for Spring Security
},
success : (data) =>{
console.log("SUCCESS : ", data);
alert(data);
},
error : (e)=> {
console.log("ERROR: ", e);
},
done : function(e) {
alert("DONE : " + e.toString());
console.log("DONE");
}
});
The controller
#ResponseBody()
#RequestMapping(value = "/likeMessage", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public AjaxResponseBody likeWithAjax(#RequestBody() AjaxRequestBody request) {
AjaxResponseBody result = new AjaxResponseBody();
//some logic
return result
}
The AjaxRequestBody and AjaxResponseBody classes
private class AjaxRequestBody{
int id;
}
private class AjaxResponseBody{
String message;
}
I'm sure that I am missing something obvious but I can't seem to figure this one out.
Thank you for your help
Remove ResponseBody() annotation from the Controller Method. Make sure you have added RestCOntroller annotation in the Controller Class.
Add produces = "application/json" in RequestMapping

How to send post ajax request from (.js) file to Spring MVC Controller?

(.js)
$.ajax({
type: "POST",
//contentType : "application/json",
dataType : "json",
url: "getStateNames",
//url:"http://localhost:8081/Mining_22_11_17/pages/admin/a.jsp",
cache: false,
data: "region=" + re + "& stId=" + state_id,
success: function(response){
//$('#result').html("");
alert("hiiii state list");
var obj = JSON.parse(response);
alert("state list" + obj);
//$('#result').html("First Name:- " + obj.firstName +"</br>Last Name:- " + obj.lastName + "</br>Email:- " + obj.email);
},
error: function(){
alert('Error while request..');
}
});
Spring MVC Controller
#RequestMapping(value="/getStateNames",method = RequestMethod.POST)
public #ResponseBody RegionDistrict add(HttpServletRequest request, HttpServletResponse response,#RequestParam String region, #RequestParam String stId) {
System.out.println("Get state");
}
By running this program I am getting 404 error.I want to send request using POST only.
$("#yourID").click(function(event) {
var region = $('#id').val();
var state_id = $('#edited').val();
$.post("${pageContext.request.contextPath}/getStateNames", {
region : region ,
state_id : state_id
}, function(data) {
//var json = JSON.parse(data);
//...
}).done(function(data) {
alert("hiiii state list");
swal("success");
//location.reload();
}).fail(function(xhr, textStatus, errorThrown) {
}).complete(function() {
//$("#btn-save").prop("disabled", false);
});
});
try this hope its works fine
$.ajax({
type: "POST",
url: "/getStateNames",
data: { region: re, stId: state_id },
success : function(response) {
alert(JSON.stringify(resoinse));
},
error: function(){
alert('Error while request..');
}
});
This should work, tell me if this solves your problem

How to implement Antiforgerytokens with partial views in mvc4?

I am trying to implement antiforgerytoken in my project. I am able to implement it when making ajax call below.
function docDelete(id) {
var _upload_id = $("#docId").val();
var _comments = $("#name").val();
var forgeryId = $("#forgeryToken").val();
$("#dialog-form").dialog("open");
$.ajax({
type: 'GET',
cache: false,
url: '/DeleteDocument/Delete',
dataType: 'json',
headers: {
'VerificationToken': forgeryId
},
data: { _upload_id: _upload_id, _comments: _comments },
success: function (data) {
$('#dialog-form').dialog('close');
$('#name').val('');
$('#dvSuccess').val(data);
Getgridata(data);
}
});
}
above code works fine. But in some cases i am making ajax request as below.
var forgeryId = $("#forgeryToken").val();
function GetGrid() {
$.ajax(
{
type: "GET",
dataType: "html",
cache: false,
url: '/Dashboard/GetGridData',
headers: {
'VerificationToken': forgeryId
},
success: function (data) {
$('#dvmyDocuments').html("");
$('#dvmyDocuments').html(data);
}
});
}
Above code does not send any token to below method.
private void ValidateRequestHeader(HttpRequestBase request)
{
string cookieToken = string.Empty;
string formToken = string.Empty;
string tokenValue = request.Headers["VerificationToken"]; // read the header key and validate the tokens.
if (!string.IsNullOrEmpty(tokenValue))
{
string[] tokens = tokenValue.Split(',');
if (tokens.Length == 2)
{
cookieToken = tokens[0].Trim();
formToken = tokens[1].Trim();
}
}
AntiForgery.Validate(cookieToken, formToken); // this validates the request token.
}
}
In layout.cshtml i have implmented code to get token.
<script>
#functions{
public string GetAntiForgeryToken()
{
string cookieToken, formToken;
AntiForgery.GetTokens(null, out cookieToken, out formToken);
return cookieToken + "," + formToken;
}
}
</script>
<input type="hidden" id="forgeryToken" value="#GetAntiForgeryToken()" />
The variable tokenValue catching null each time. So what i understood is through headers i am not able to send token value. I tried many alternatives. So anyone suggest me how can i overcome this issue? Thank you in advance.
I tried as below still i am getting null value.
var token = $('[name=__RequestVerificationToken]').val();
var headers = {};
headers["__RequestVerificationToken"] = token;
alert(token);
var forgeryId = JSON.stringify($("#forgeryToken").val());
function GetGrid() {
$.ajax(
{
type: "GET",
dataType: "html",
cache: false,
url: '/Dashboard/GetGridData',
cache: false,
headers: headers,
success: function (data) {
$('#dvmyDocuments').html("");
$('#dvmyDocuments').html(data);
}
});
}

Resources