Error post AJAX from Spring JAVA - javascript

I already created MVC spring and I want consume with SAPUI5 (javascript) with AJAX but I found an error "415 (Unsupported Media Type)". I use swagger in spring for test CRUD. in swagger, I success for insert data but failed in AJAX.
controller Spring:
#PostMapping(value={"/tesinsert"}, consumes={"application/json"})
#ResponseStatus(HttpStatus.CREATED)
public ResponseEntity<?> insert(#RequestBody KasusEntity user) throws Exception {
Map result = new HashMap();
userService.insertTabel(user);
return new ResponseEntity<>(result, HttpStatus.CREATED);
}
in javascript:
var data = {
"kodekasus":5,
"nama":"baru",
"isdelete":1,
"createdby":"hahaa",
"createddate":null,
"updatedby":"hihii",
"updateddate":null
};
$.ajax({
type: 'POST',
url: url,
data: data,
success: function(data) {
console.log('sukses: '+data);
},
error: function(error){
console.log('gagal: '+error);
}
});
if I code above in AJAX, show error "415 (Unsupported Media Type)", if I add in AJAX show different error: "Response for preflight has invalid HTTP status code 403
":
headers: {
Accept : "application/json; charset=utf-8",
"Content-Type": "application/json; charset=utf-8"
}
How to solve this problem?
Thanks.
Bobby

Add dataType: 'json' in your ajax call:
$.ajax({
type: 'POST',
url: url,
data: data,
dataType: 'json',
success: function(data) {
console.log('sukses: '+data);
},
error: function(error){
console.log('gagal: '+error);
}
});

Related

Why i am getting 406 not accepatble at client side status by the server and even my spring controller is not calling?

Here is my code
ajax get request code
$("#tabsss2").click(function tab1()
{
$.ajax({
type: "get",
traditional: true,
dataType: 'json',
url: "DataGridServlet.htm",
cache: false,
success: function (response) {
alert(response);
}
});
console.log("hii");
});
and controller code is what i have written as controller
#RequestMapping(value="/DataGridServlet.htm", method = RequestMethod.GET,produces="application/json")
public #ResponseBody JSONObject getReturnData()
{
System.out.println("control came into conroller");
JSONObject dataObject=new JSONObject();
dataObject=jqTabsGridDataDao.getTabsData();
System.out.println("controller data:"+dataObject);
return dataObject;
}
so any one can help?
add the following header in ajax request
headers: {
Accept: "application/json"
}

HTTP Authentication failing in AJAX for postmates api

I'm trying to use the postmates API, which first requires us to authenticate ourselves using http basic authentication. The username field in the code below is where we inserted our private API key.
<script>
$(document).ready(function(){
// Request with custom header
$.ajax({
url: ' http://username:#api.postmates.com',
type: 'GET',
dataType: 'jsonp',
success: function(response) { alert("Success"); },
error: function(error) {alert(error); }
});
});
</script>
The error we are getting is
XMLHttpRequest cannot load
http://api.postmates.com/?callback=jQuery112008309037607698633_1462052396724&_=1462052396725.
Response for preflight is invalid (redirect)
need the authentication
https://postmates.com/developer/docs#authentication
The actual header that is used will be a base64-encoded string like
this:
Basic Y2YyZjJkNmQtYTMxNC00NGE4LWI2MDAtNTA1M2MwYWYzMTY1Og==
Try to
$(document).ready(function(){
// Request with custom header
$.ajax({
url: ' http://username:#api.postmates.com',
type: 'GET',
dataType: 'jsonp',
success: function(response) { alert("Success"); },
error: function(error) {alert(error); },
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Basic Y2YyZjJkNmQtYTMxNC00NGE4LWI2MDAtNTA1M2MwYWYzMTY1Og==");
}
});
});
I don't test because jsfiddle block external petitions.

Calling Google Protocol RPC API in Browser via JavaScript

I'm trying to access a Google Protocol RPC API with jQuery like this:
jQuery.ajax({
url: some_url,
type: "POST",
data : some_params,
contentType: "application/json; charset=utf-8",
dataType : "json",
success : function (data) {
console.log(data);
},
error : function (xhr, status, errorThrown) {
console.log(xhr);
}
});
But I only get the following error message:
XMLHttpRequest cannot load https://*****. Response for preflight has invalid HTTP status code 400
How can I return an OPTIONSmethod in ProtoRPC, that I don't get this error anymore?

"400 Bad Request" response for AJAX request

I have the following jQuery AJAX request:
// collect form data and create user obj
var user = new User();
user.firstname = $("#usrFirstName").val();
user.lastname = $("#usrSurname").val();
user.role = $("#usrRole").val();
// actual ajax request
$.ajax({
type: 'POST',
url : 'http://awesome-url',
crossDomain: true,
data: user,
contentType:"application/json; charset=utf-8",
dataType: 'json'
}).done(function(data, status) {
alert(JSON.stringify(data));
}).fail(function(data, status) {
alert(status);
alert(JSON.stringify(data));
});
The response from the Server is:
"status":400,"statusText":"Bad Request"
"The request sent by the client was syntactically incorrect."
The server is running Spring-MVC. But as far as I can tell it is working correctly. Because if I'm sending a request manually with Postman and the following configuration it works.
Header:
Content-Type application/json; charset=utf-8
Content:
{"firstname":"alex","lastname":"lala","role":"admin"}
I have to mention that it is a cross-domain request (for the time developing, it will be hosted on the same domain as the server later). I did disable the security settings in the browser and AJAX requests to the server are working fine (as long as I don't have to send data).
you need to serialize your json, try:
$.ajax({
type: 'POST',
url : 'http://awesome-url',
crossDomain: true,
data: JSON.stringify(user),
contentType:'application/json; charset=utf-8',
dataType: 'json'
})
JSON.stringify() method is used to turn a javascript object into json string. You need to have this. In addition it is better to include success and error portions in the AJAX.
$.ajax({
type: 'POST',
url : 'http://awesome-url',
crossDomain: true,
data: JSON.stringify(user), // turn a javascript object into json string
contentType:'application/json; charset=utf-8',
dataType: 'json',
success: function (html) {
alert(html);
}, error: function (error) {
alert(error);
}
})

sending url in ajax jquery and getting response null

I have client URL and getting response from that URL through browser. While sending through AJAX I am getting a null response. Right now I am working with a .Net application. Here I am given my script. Please guide me to get proper response and thanks in advance.
Response:
{
"resultFlag": false,
"message": "Dealer not found",
"info": []
}
$.ajax({
type: "GET", //GET or POST or PUT or DELETE verb
url: URL,
//data: data,
dataType: "json",
contentType: "application/json; charset=utf-8", // content type sent to server
success: function (result) {
// JSON.stringify(result);
alert(JSON.stringify(result));
},
error: function () {
alert('error');
}
});

Categories