Here is my angular app.js code
$http({
method: 'GET',
url: 'http://localhost:8080/GngWebservice/rest/GngService/FeetToInch'
//webservice url
}).success(function(data, status) {
$scope.status = status;
$scope.data = data;
}).
error(function(data, status) {
console.log(data);
$scope.data = data || "Request failed";
$scope.status = status;
});
and my rest web service (java) using jersey) method is :
#Path("/FeetToInch")
#GET
#Produces(MediaType.APPLICATION_JSON)
public Response getoutput() throws JSONException {
JSONObject json=new JSONObject();
JSONObject HEADER=new JSONObject();
JSONObject RESPONSE=new JSONObject();
json.put("name", "hello");
HEADER.put("status","200");
RESPONSE.put("data", "hello");
json.append("HEADER", HEADER);
json.append("RESPONSE", RESPONSE);
String results=""+json;
System.out.println(results);
return Response.status(200).entity(results).build();
}
want ot send json as a response but it always show failed
can any body tell me how to find which error occurred
Related
I am new to jquery/Ajax .
My Server code return the json data
But it did not received in jquery/ajax .
for which i have tried
this is my ajax request code
$.ajax({
type: 'post',
url:'http://localhost:8080/eduvib/webapi/question/getPaper',
dataType:'json',
data: {"subject":subject,"cls":classes,"diff":dificultylevel,"marks":marks},
success:function(response) {
alert(JSON.stringify(response));
},
error:function() {
alert("request failed");
}
});
And this is my server Side Code Which also return the response
#POST
#Path("/getPaper")
#Consumes({MediaType.APPLICATION_FORM_URLENCODED,MediaType.APPLICATION_JSON})
#Produces(MediaType.APPLICATION_JSON)
public List<Question> getPaper(#FormParam("subject") String subject, #FormParam("cls") String cls,
#FormParam("diff") int diff, #FormParam("marks") int marks) throws Exception {
ArrayList<Question> mylist = new ArrayList<Question>();
mylist = getQuestionList.getData(subject, cls, diff, marks);
System.out.println(mylist);
return mylist;
}
And this is the Logs at server side which prints the response after hitting the ajax request
[Question [questionid=questionid, questiontext=kk, topicname=k,...... complete list
But in Ajax request its not getting
I have a web service made witj Java and Jersey. I want to receive a JSON request and parse the json for savethe values stores on the json on the database.
This is mi web service code:
#Path("companies")
public class Companies {
#Path("add")
#POST
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public JSONObject addCompanies(JSONObject inputJsonObj){
String input = (String) inputJsonObj.get("company");
String output = "The input you sent is :" + input;
JSONObject outputJsonObj = new JSONObject();
outputJsonObj.put("output", output);
return outputJsonObj;
}
}
The client side is made with AngularJS:
$scope.company = "";
$scope.submit = function(){
// Writing it to the server
//
var dataObj = {
company : $scope.company
};
var res = $http.post('http://localhost:8080/WS-Test2/crunchify/companies/add', dataObj);
res.success(function(data, status, headers, config) {
$scope.message = data;
notify("succes");
});
res.error(function(data, status, headers, config) {
//alert( "failure message: " + JSON.stringify({data: data}));
notify("fail");
});
};
This is the error I'm getting when I pass the JSON to the web service:
Status Code:415
And this is the request I am sending:
{"company":"Testing2"}
This is my Network tab:
Without further configuration, JSONObject is not something that Jersey supports. You will just need to work with Strings
public String addCompanies(String json){
JSONObject inputJsonObj = new JSONObject(json)
String input = (String) inputJsonObj.get("company");
String output = "The input you sent is :" + input;
JSONObject outputJsonObj = new JSONObject();
outputJsonObj.put("output", output);
return outputJsonObj.toString();
}
If you really want to use JSONObject you can check out this post.
See Also:
JAX-RS Entity Providers to learn how Jersey handle serialization an deserialization.
I have created a spring controller and a jsp page. In jsp page I am using jquery ajax call to hit the controller. Now, this controller returns a json response as string. Now on based of json response in success method, I want to call a next controller call which will return a ModelAndView jsp page. How can I do this. Below is my code:
JSP Jquery ajax call:
$(document).ready(function(){
$("#submitButton").click(function(e){
var formData = getFormData();
if(formData!=false){
$.ajax({
type: 'POST',
'url': 'http://localhost:8080/Test_ReportingUI/fieldMappingNext.htm',
data: {jsonData: JSON.stringify(formData)},
dataType: 'json',
success: function(response){
try{
var strResponse=jQuery.parseJSON(response);
}catch(err){}
if(response.status=='ok')
{
alert ("okokokokokokokokok");
//I am successfully reaching till here.
//But in case of this alert box I want to call a
//controller which will return ModelAndView and
//should open a corresponding ModelAndView jsp page.
//something like:
/*
$.ajax({
type: 'GET',
'url': 'http://localhost:8080/Test_ReportingUI/abcxyz.htm',
)};
*/
}
else
{
alert("ERROR!!");
}
},
timeout: 10000,
error: function(xhr, status, err){
if(response.status=='timeout')
{
alert('Request time has been out','');
}
console.log(status,err);
}
}); }
});
});
Controller class methods:
#RequestMapping (value="fieldMappingNext.htm", method=RequestMethod.POST)
#ResponseBody String addFieldMappingNext(#RequestParam String jsonData)
{
String customerID =null;
String objectID = null;
String syncFieldName = null;
String optMapping = null;
JSONObject jsonResponse = new JSONObject();
try{
JSONObject requestedJSONObject = new JSONObject(jsonData);
customerID = requestedJSONObject.getString("customerID");
objectID = requestedJSONObject.getString("objectID");
syncFieldName = requestedJSONObject.getString("syncFieldName");
optMapping = requestedJSONObject.getString("optMapping");
}catch(Exception exex){
exex.printStackTrace();
}
if(optMapping.equalsIgnoreCase("direct")){
long metadataID=rwCustomerService.getMetaDataID(customerID,objectID);
List<RWFieldDetail> list=rwCustomerService.getFieldDetailNames(metadataID);
request.setAttribute("customerID", customerID);
request.setAttribute("objectID", objectID);
request.setAttribute("optMapping", optMapping);
request.setAttribute("syncFieldName", syncFieldName);
request.setAttribute("fieldNames", list);
try {
jsonResponse.put("status", "ok");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return jsonResponse.toString();
}
Second Controller method that I want to call from jquery success method:
#RequestMapping (value="abcxyz.htm", method=RequestMethod.GET)
ModelAndView fieldMapping(){
ModelAndView modelAndView=new ModelAndView("FieldMappingMainScreenNext");
return modelAndView;
}
How do I do this.
Since the second handler method returns ModelAndView, you should redirect from the success callback:
...
success: function(response) {
window.location.replace(response.url);
}
...
In your Java code you can use something like:
Map<String, String> map = new HashMap<String, String>();
if(condition1){
map.put("url","url1.html");
}
if(condition2){
map.put("url","url2.html");
}
Convert it to a JSON string and revert it back. Afterwards, in the jquery portion you'll get the response:
success:function(jsonStr){
var obj = JSON.parse(jsonStr);
var url = obj.url;
}
That is how you can get the url. If you want to load an other page or create an ajax call then you can do it.
I have a Spring MVC controller being called by AJAX and returns JSON. If the call succeeds without error, I am returning a string message with the key "message". Likewise, if an exception is caught, I return a string error also with the key "message". I also return a HTTP error response.
In my Javascript, I output this "message" in an alert. The alert displays the message in the event of a successful call. If the call is unsuccessful, I get a Javascript error that "data is undefined".
Why is "data" accessible when successful but not when the call fails, and what correction do I need to make this work?
I am a newbie to AJAX calls with Spring so any general feedback/critique of my solution below is welcome and appreciated.
N.B. The alerts in the Javascript and the messages themselves are dummy implementations until I correctly provide user feedback by modifying the DOM.
The Controller
#RequestMapping(value = "/getMovieData", method = RequestMethod.POST, produces = "application/json")
#ResponseBody
public Map<String, Object> getMovieData(#RequestBody Map<String, Object> json, HttpServletResponse response) {
String movieId = json.get("id").toString();
Map<String, Object> rval = new HashMap<String, Object>();
try {
Movie movie = movieService.getMovieData(movieId);
rval.put("message", "You have succeeded");
rval.put("movie", movie);
} catch (Exception e) {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
rval.put("message", "You have an error - " + e.getMessage());
}
return rval;
}
The Javascipt
function getMovieData(data) {
var request = $.ajax({
type : 'POST',
url : '<c:url value="/getMovieData" />',
dataType : "json",
contentType : "application/json; charset=utf-8",
data : data,
});
request.done(function(data) {
alert("Success: " + data.message);
populateMovieFields(data.movie);
});
request.fail(function(xhr, status, error, data) {
alert("status: " + status);
alert("error: " + error);
alert("Fail: " + data.message);
});
}
The JSON response is available inside the jqXHR object passed as the first parameter.
request.fail(function(jqXHR, textStatus, errorThrown) {
alert("Fail: " + jqXHR.responseJSON.message);
});
I was able to get a #GET request working on jersey and the relevant code is as follows
The code for the server
#Path("/Text")
#GET
public String Hello() {
System.out.println("Text Being print");
return "Abc";
}
#POST
#Path("/post/{name}/{gender}")
public Response createDataInJSON(#PathParam("name") String data, #PathParam("gender") String data2) {
System.out.println("Post Method 1");
JSONObject obj = new JSONObject();
obj.put("Name", data);
obj.put("Gender", data2);
return Response
.status(200)
.entity(obj.toJSONString())
.build();
}
The #POST also works when the parameters are passed in the url. (as mentioned in the above code segment)
But, it doesn't work when the parameters are not sent via the url. Like the code which follows.
#POST
#Path("/post2")
public Response createDataInJSON2(#FormParam("action") String data) {
System.out.println("Post Method 2 : Data received:" + data);
JSONObject obj = new JSONObject();
obj.put("data", data);
return Response
.status(200)
.entity(obj.toJSONString())
.build();
}
May be the problem lies with the way the services are called.
//GET call (Plain Text)
System.out.println(service.path("Hello").accept(MediaType.TEXT_PLAIN).get(String.class));
//POST call (Param)
ClientResponse response = service.path("Hello/post/Dave/Male").post(ClientResponse.class);
System.out.println(response.getEntity(String.class));
//POST call (JSON)
String input = "hello";
ClientResponse response2 = service.path("Hello/post2").post(ClientResponse.class, input);
System.out.println(response2.getEntity(String.class));
Can anyone tell me what am I missing here?
Try to add a #Consumes (application/x-www-form-urlencoded) on your #POST method createDataInJSON2 and explicitly add the same mime type in your request service.path("Hello/post2").type(MediaType.APPLICATION_FORM_URLENCODED).post(ClientResponse.class, input).
Also consider that your input is just a simple string. Have a look at the class MultivaluedMap
If you have troubles with the Encoding then have a look at this post https://stackoverflow.com/a/18005711/3183976
Try this. This worked for me.
The post method:
#POST
#Path("/post2")
public Response post2(String data) {
System.out.println("Post method with File: " + data);
return Response
.status(200)
.entity(data)
.build();
}
The calling method:
ClientResponse response2 =service.path("Hello/post2").post(ClientResponse.class,"some value");
System.out.println(response2.getEntity(String.class));
Hope this helps. Peace.