I am sending a post request using jquery Ajax to java Restful Webservice. Request is submitted successfully but no response is coming back.
Jquery Code
$.ajax({
type: "POST",
url: "http://127.0.0.1:8080/Sampleprj/getData",
data: "{\"result\": \"Hello\"}",
crossDomain: true,
dataType: "json",
success: function( data, textStatus, jqXHR) {
},
error: function(jqXHR, textStatus, errorThrown){
},
beforeSend: function(jqXHR, settings){
},
complete: function(jqXHR, textStatus){
}
});
Java Code :-
#RequestMapping(method=RequestMethod.POST, value="/getData")
public #ResponseBody String getRequest(#RequestBody String data) {
System.out.println(data);
return "{\"result\": \"Hello\"}";
}
Data coming from jquery is successfully printed to console but no data is returning back to jquery. It is going in error function and showing 200 OK status in firebug console without any response.
Related
Whats wrong in my approach.
Java Mapping :
#POST
#Path("/receive")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public void consumeJSONList(#RequestBody List<Question> clientList) {
String output = "consumeJSONList Client : " + clientList.toString() + "\n\n";
System.out.println(output);
}`
Ajax Call :
function addData(x) {
var x='[{"id":12,"email": "2","lang": "es"}]';
$.ajax({
type: 'POST',
url: "rest/question/receive",
header : {
"Content-Type":"application/json"
},
data: x,
success: function(data, textStatus, jqXHR){
alert('Wine created successfully');
},
error: function(jqXHR, textStatus, errorThrown){
console.log(jqXHR);
alert(jqXHR+'addWine error: ' + textStatus+"errorThrown"+errorThrown);
}
});
}
i am able hit the same url with same data in google post man but when use ajax call its throwing 415(Unsupported media type)
Please help to create a controller which can accept list of java object and process the same
As the jQuery docs say, you should give the following a try:
Replace…
header : {
"Content-Type":"application/json"
},
…with…
dataType: 'json',
…and make sure that the server's context path in front of "/receive" is really "rest/question". Depending on the situation also a leading slash "/rest/question/receive" could be worth a try.
I have the following javascript in my test html page to send ajax requests to a java restful web service I built with netbeans (mostly auto generated by using 'Restful web services from database' function).
Here is the ajax query from my test html page:
$(function(){
$('.message-button').on('click', function(e){
var resultDiv = $("#resultDivContainer");
$.ajax({
headers: { 'Accept': 'application/json',
'Content-Type': 'application/json'
},
'type': 'POST',
'url': 'http://localhost:8080/xxxAPI/api/activity',
'data': { "baseItemId": "2" },
'dataType':'json',
'success': function(data) {
var xmlstr = data.xml ? data.xml : (new XMLSerializer()).serializeToString(data);
$("#resultDivContainer").text(xmlstr);
},
'error': function(jqXHR, textStatus, errorThrown) {
alert(' Error in processing! '+textStatus + 'error: ' + errorThrown);
}
});
})
});
Also here is the part of my java code that accepts post requests:
#POST
#Override
#Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public void create(XxxxxActivity entity) {
super.create(entity);
}
When I request from the test page (for this version of the test page), I get this error:
Failed to load resource: the server responded with a status of 415
(Unsupported Media Type)
or this error:
POST http://localhost:8080/xxxAPI/api/activity 415 (Unsupported
Media Type)
So far I have tried making various changes to the ajax request as advised on similar questions on stackoverflow, including changing type to jsonp, putting json data in double quotes, adding headers and changing data type to xml. None of them have worked.
Also since I manage to get a response from the server at times, I wonder if the issue is with xml parsing in the java code. I believe a potential fix would be to add the jackson jar files, but I have no idea how to add them on netbeans as there is no lib folder in WEB_INF.
I would also like to know if there is any issue with the jquery ajax request. This issue has been bugging me for days.
PS: Also note that GET requests from the browser work fine. I have not used maven in this project.
Replace
'data': { "baseItemId": "2" },
with
'data': JSON.stringify({ "baseItemId": "2" }),
Object JSON is available here.
EDIT
add attribute contentType: 'application/json; charset=UTF-8'
remove attribute headers from ajax call.
Frondend
$.ajax({
contentType: "application/json; charset=utf-8",
url: '/GetList',
type: 'POST',
dataType: 'json',
data: JSON.stringify({ 'Name': 'mehmet erdoğdu'}),
beforeSend: function () {
}, success: function (data) {
}, complete: function () {
}, error: function (data) {
}
});
Backend
[HttpPost]
public JsonResult GetList([FromBody] NameRequest req)
{
var selectListItems = new List<SelectListItem>
{
new SelectListItem
{
Value = "",
Text = "Select Name"
}
};
//
return Json(selectListItems, new JsonSerializerSettings());
}
During page load JSONP executes error block while making an ajax call even though the status is 200 OK and the error text is "parseerror". But the same ajax call executes success block when it is called on some click event from UI.
$.ajax({
crossDomain : true,
type : "GET",
contentType : "application/json; charset=utf-8",
dataType : "jsonp",
jsonpCallback : 'success',
url : "rest/getRecommendation",
cache: false,
timeout : 15000,
then : function(data) {
},
error : function(responseData, textStatus, errorThrown) {
In my app I want to respond from server to client the status of the operation, for example, from client sends data in format json to server and I want that this responds whit status of the operation, if these data have inserted correctly in database to send status 200,...
I now have this.
Client:
function sendAjax() {
//I build the params necessary to send to server in format json
$.ajax({
url: "/url",
type: 'POST',
dataType: 'json',
data: param,
contentType: 'application/json',
mimeType: 'application/json',
success: function(data) {
alert(data.id );
},
error: function(data,status,er) {
alert("error: "+data+" status: "+status+" er:"+er);
}
});
alert();
}
Server:
Controller.java
#RequestMapping(value = "/", method = RequestMethod.POST)
public #ResponseBody
ResponseJson post (#RequestBody String string){
//I have the operations necessary to insert in database
ResponseJson pruebaJson = new ResponseJson ();
pruebaJson.setId (id);
return pruebaJson;
}
ResponseJson.java
public class ResponseJson implements Serializable
{
private String id;
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
}
How will I process the status that server send to client? this is, if I get status 200 or other status.
My app is realized in spring-mvc and I use javascript with ajax to send data in format json from client to server.
Thanks
You can do it by :
$.ajax({
statusCode: {
404: function() {
alert( "page not found" );
},
200: function() {
alert("insert done..!!!");
},
}
});
This may help you.
See JQuery API for more option.
EDIT : on the basis of my understanding you want to check status code inside success or error function for that
success: function(data , textStatus, jqXHR) {
alert(data.id );
var statusCode = jqXHR.status
if(statusCode == 200 ){
//Your code execute if status is 200
}
}
like wise you can do it in error function also.
In your ajax call success function executes when server sends status 200 code. other than that your error function only executes.
If you want to handle error status separately you can handle in error function with return status.
I am trying to collect all the form data and send it as a XML to Controller. This XML will further be sent to back end which will take care of it.
There is no need to marshal this XML into an Object.After receiving this XML I just need to send a String success message back.
It is half working. I am able to receive XML message from UI page and able to print it on console. But when I just send success message back UI ajax call receives No conversion from text to application/xml
#RequestMapping(value="/save",method=RequestMethod.POST,consumes={"application/json", "application/xml", "text/xml","text/plain"})
#ResponseBody public String handleSave(#RequestBody String formData)
{
System.out.println("comes here");
System.out.println(formData);
return "Success";
}
$('form').submit(function () {
$.ajax({
url: $(this).attr('action'),
type: 'POST',
processData: false,
data: collectFormData1(),
headers: {
"Content-Type":"application/xml"
},
dataType: 'application/xml',
success: function (data) {
alert('Success:'+data)
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('jqXHR:'+jqXHR+'\n'+'textStatus:'+'\n'+textStatus+'errorThrown::'+errorThrown);
}
});
return false;
});
Try to remove dataType: 'application/xml' from jquery code.
As mentioned in documentation: DataType: The type of data that you're expecting back from the server.
(http://api.jquery.com/jQuery.ajax/)