In ftl file, I have ajax like this here while firing ajax, I get 404 Not found error, though all things fine,
$.CustomService.execute("/policyDetails/"+$(this).attr('data-cancel-id')+"/policyList.json", {
method : "GET",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
success : function(response) {
alert("Success");
console.log(response);
},
error : function() {
alert("Error");
}
});
In Controller
#Controller
#RequestMapping("/cancellationPolicyDetails")
{
..........
..........
#RequestMapping(value = "/{id}/policyList", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})
#ResponseBody
public CancellationPolicyDetailDTO getDetails(#PathVariable Long id) {
return this.service.findOne(id);
}
}
Related
Trying to be more consistent with HTTP verbs, I'm trying to call a delete Handler on a Razor Page via AJAX;
Here's my AJAX code, followed by the C# code on my page :
return new Promise(function (resolve: any, reject: any) {
let ajaxConfig: JQuery.UrlAjaxSettings =
{
type: "DELETE",
url: url,
data: JSON.stringify(myData),
dataType: "json",
contentType: "application/json",
success: function (data) { resolve(data); },
error: function (data) { reject(data); }
};
$.ajax(ajaxConfig);
});
my handler on my cshtml page :
public IActionResult OnDeleteSupprimerEntite(int idEntite, string infoCmpl)
{
// my code
}
which never reaches ... getting a bad request instead !
When I switch to a 'GET' - both the type of the ajax request and the name of my handler function ( OnGetSupprimerEntite ) - it does work like a charm.
Any ideas ? Thanks !
Short answer: The 400 bad request indicates the request doesn't fulfill the server side's needs.
Firstly, your server is expecting a form by;
public IActionResult OnDeleteSupprimerEntite(int idEntite, string infoCmpl)
{
// my code
}
However, you're sending the payload in application/json format.
Secondly, when you sending a form data, don't forget to add a csrf token:
#inject Microsoft.AspNetCore.Antiforgery.IAntiforgery Xsrf
<script>
function deleteSupprimerEntite(myData){
var url = "Index?handler=SupprimerEntite";
return new Promise(function (resolve, reject) {
let ajaxConfig = {
type: "DELETE",
url: url,
data: myData ,
success: function (data) { resolve(data); },
error: function (data) { reject(data); }
};
$.ajax(ajaxConfig);
})
}
document.querySelector("#testbtn").addEventListener("click",function(e){
var myData ={
idEntite:1,
infoCmpl:"abc",
__RequestVerificationToken: "#(Xsrf.GetAndStoreTokens(HttpContext).RequestToken)",
};
deleteSupprimerEntite(myData);
});
</script>
A Working Demo:
Finally, in case you want to send in json format, you could change the server side Handler to:
public class MyModel {
public int idEntite {get;set;}
public string infoCmpl{get;set;}
}
public IActionResult OnDeleteSupprimerEntite([FromBody]MyModel xmodel)
{
return new JsonResult(xmodel);
}
And the js code should be :
function deleteSupprimerEntiteInJson(myData){
var url = "Index?handler=SupprimerEntite";
return new Promise(function (resolve, reject) {
let ajaxConfig = {
type: "DELETE",
url: url,
data: JSON.stringify(myData) ,
contentType:"application/json",
headers:{
"RequestVerificationToken": "#(Xsrf.GetAndStoreTokens(HttpContext).RequestToken)",
},
success: function (data) { resolve(data); },
error: function (data) { reject(data); }
};
$.ajax(ajaxConfig);
})
}
document.querySelector("#testbtn").addEventListener("click",function(e){
var myData ={
idEntite:1,
infoCmpl:"abc",
};
deleteSupprimerEntiteInJson(myData);
});
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
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);
}
});
}
I developed a WebApi and Client page for testing.
Here is my controller
public class CarDetailsController : ApiController
{
// GET api/cardetails
[HttpGet]
public IEnumerable<CarsStock > GetAllcarDetails()
{
CarsStock ST = new CarsStock();
CarsStock ST1 = new CarsStock();
List<CarsStock> li = new List<CarsStock>();
ST.CarName = "Maruti Waganor";
ST.CarPrice = "4 Lakh";
ST.CarModel = "VXI";
ST.CarColor = "Brown";
li.Add(ST);
ST1.CarName = "Maruti Swift";
ST1.CarPrice = "5 Lakh";
ST1.CarModel = "VXI";
ST1.CarColor = "RED";
li.Add(ST1);
return li;
}
}
and here is my ajax call
<button onclick="AllcarDetails()"></button>
<script type="text/javascript">
function AllcarDetails()
{
$.ajax({
type: "GET",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
contentType: 'application/json',
url: "http://localhost:1822/api/cardetails", //URI
success: function (data) {
debugger;
var datadatavalue = data;
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
</script>
It gives 405 Method Not Allowed error all the time.I tried by googling but cannot find the exact situation.Can somebody help me to solve this?
Got result correctly while calling from browser 'http://localhost:1822/api/cardetails'
Did you check so that HTTP Activation is activated where you run this code?
I am using spring MVC and JQuery ajax. In one of my ajax call it returns large amount of data it nearly takes 5 minutes.
In Ajax method shows error even though the response came i checked it through firebug.
my ajax coding is
jQuery(document).ready(function () {
jQuery("sampleSearch").click(function () {
jQuery("body").addClass("loading");
var formValues = jQuery('#sample-search-form').find(':input[value][value!=""]').serialize();
jQuery.ajax({
type: "GET",
url: "/sample/user-byName",
data: formValues,
dataType: 'json',
success: function (data) {
jQuery('#json').val(JSON.stringify(data)).trigger('change');
jQuery('body').removeClass("loading");
},
error: function (e) {
alert('Error while request..' + e.toLocaleString());
jQuery('body').removeClass("loading");
}
});
});
});
and in my controller
#RequestMapping(value = "/user-byName", method = RequestMethod.GET)
#ResponseStatus(HttpStatus.OK)
public
#ResponseBody
String getUserByName(HttpServletRequest request) {
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
Integer page = Integer.parseInt(request.getParameter("page"));
String resultJson = getUserByName(firstName, lastName, page);
return resultJson;
}
You need to increase the timeout for the request.
jQuery.ajax({
type: "GET",
url: "/sample/user-byName",
data: formValues,
dataType: 'json',
timeout: 600000,
success: function (data) {
jQuery('#json').val(JSON.stringify(data)).trigger('change');
jQuery('body').removeClass("loading");
},
error: function (e) {
alert('Error while request..' + e.toLocaleString());
jQuery('body').removeClass("loading");
}
});
read more in the .ajax() documentation