AJAX POST and RESTFul Web Services not working on IE 11 - java

I have an AJAX call to a JAVA POJO as follows -
$.ajax({
url:'./webapi/input/approve',
type: 'PUT',
data:jsonobj,
contentType: 'application/json',
dataType:'json',
success:function(data)
{
if(!data){
alert("Invalid");
}
var values = JSON.stringify(data);
alert(values);
},
error:function(xhr,textstatus,errorthrown){
alert(xhr.responseText);
alert(textstatus);
alert(errorthrown);
}
},'json');
The corresponding Constructor in the Java Pojo that I have is as follows -
public Input(String LR, double ECH,
double CSH,String App) {
this();
lr = LR;
ech = ECH;
csh = CSH;
app = App;
}
In addition to this, I also have another Parameterised and Default Constructor in the same class. The issue that I am facing is that when I run my .jsp page, This parameterised constructor above should get called. However, When I run the same, the desired constructor does not get called. Please note that I am running Internet Explorer v 11. Also note that when I run the same on Chrome, I get the desired output.
Help much appreciated!

Related

Illegal argument: . . . exception in . . . with cause = null

I am trying to add functionality to an existing JAVA Spring/Angular JS web application that uses REST calls along with JPA/Hibernate/Liquibase. I have followed what is there and while I have worked through a lot of errors I cannot figure out what is hopefully the last error. The application loads but there is no data returned to display. And I know the data is in the database as a direct SQL query pulls it back. So it has to be with the Spring/JPA/Hibernate setup. I see in the logs that the Angular controller calls my PropertiesRestController.java file and uses the correct method. That in turn calls the correct method in my PropertiesDataService.java file which uses the correct query/method in my Repository.java file. But when I debug the point of breakdown the code appears to breakdown in the AngularJS service on the line "data = angular.fromJson(data);". The logs show the correct parameters for each method but then error out on the PropertiesRestController.java method call with ". . . logging.LoggingAspect - Illegal Argument ['Sold','30,'jwt.model.UserContext#xzyABC123',Page request[number: 0, size 20, sort: null]] in . . . . web.rest.controller.PropertiesRestController.findMyProperties() . . . logging.LoggingAspect - Exception in . . . web.rest.controller.PropertiesRestController.findMyProperties() with cause = null". Also, on the front end in the browser with developer tools I get "SyntaxError" at the "findMyProperties.transformResponse line of my AngularJS service for this page view.
I have done extensive web research on this. And I have added for example "return Optional.ofNullable(myProperty).map(a -> new ResponseEntity<>(a, HttpStatus.OK)).orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND) to the PropertiesRestController.java method call. Before I jsut tried to return Page myProperty = myPropertyDataService.getMyProperties( . . . . ). Others had issues with null being returned and needed to handle it. I am getting data for sure (if the SQL is correct) but in case the query needed adjusting I decided to at least handle the null that is reported in the log file. I've made sure my SQL in #Query is referencing entity names not tables/SQL language (although honestly some of the ones already used I don't see in the entity definitions so I don't know where they got those to use from.)
AngularJS Controller
$scope.myPropertiesP = [];
$scope.loadall = function(){
MyProperties.findMyProperties({propertyStatus:"Pending",listingDate:0,function(result){
$scope.myPropertiesP = result.content;
});
$scope.loadall();
AngularJS Service
use strict;
angular.module('propertyApp')
.factory('MyProperties',function($resource){
return $resource('rest/api/Properties/my/:propertyStatusName/:propertyListingDate', {}, {
'findMyProperties': method: 'GET',
transformResponse: function(data){
data = angular.fromJson(data);
return data;
});
});
});
PropertyRestController.java
#GetMapping(value='/properties/my/{propertyStatusName}/{propertyListingDate}", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Page<Properties>> findMyProperties(#PathVariable propertyStatusName, #PathVariable Integer propertyListingDate, #Authenticated User user, Pageable page){
Page<Properties> myProperty = myPropertyDataService.getMyProperties(propertyStatusName, propertyListingDate,user.getUser(),pageable);
return Optional.ofNullable(myProperty).map(a -> new ResponseEntity<>(a, HttpStatus.OK)).orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
}
PropertyDataServices.java
public Page<Properties> getMyProperties(String propertyStatusName, Integer propertyListingDate, User user, Pageable page){
if(pageable != null){
if(propertyListingDate==0)&&(propertyStatusName=='Pending'){
return PropertyRespository.MyPropertiesP(user.getId(),pageable);
} else {
return PropertyRespository.MyPropertiesP(user.getId(), newPageRequest(0,20));
}
}
PropertyRepository.java
public interface PropertyRespository extends JpaRepsotiory(Property,Long>{
Page<Property> findByNameContaingIgnoreCase(String name, Pageable pageable);
. . .
#Query("select prop from Property prop where prop.propertyOwner = :propertyOwnerId AND (propertyStatus=3 OR prop.propertyStatus=2) ORDER BY prop.propertListingDate DESC")
Page<Property> myPropertiesP(#Param("propertyOwner") Integer propertyOwnerId, Pageable pageable):
}
I am supposed to get back JSON strings of database objects to display through AngularJS.

struts2 ajax call response always shows null

I am trying to call the struts2 action class from my jsp using ajax. I can hit the action class and able to pass the parameters to action class. But the response that comes from action class to my ajax request is always null
All setters and getters are set correctly and they are working fine when I see in debug sysouts
Action Class
#Override
#Action(value = "/search",
results = { #Result(name = "success", type="json")})
public String execute() throws ParseException
{
this.setName(this.term+": "+this.pos);
System.out.println("Name: "+Name);
JSONObject json = (JSONObject)new JSONParser().parse(Name);
return ActionSupport.SUCCESS;
}
jsp
function Search()
{
var term = document.getElementById("term").value;
var pos = document.getElementById("pos").value;
var itr = document.getElementById("itr").value;
var pri = document.getElementById("pri").value;
var atb = document.getElementById("atb").value;
var jsonData = {};
jsonData.term = term;
jsonData.pos = pos;
jsonData.itr = itr;
jsonData.pri = pri;
jsonData.atb = atb;
$.ajax({
type: "POST",
url: "search",
dataType: "json",
data: jsonData,
success: function(response){
console.log(""+response);
alert('Name: '+response.Name);
//alert('Length: '+data[0].length);
/* $.each(data[0],function(index, value){
alert("value " +value);
});*/
},
error: function(response){
alert(response);
alert(response.length);
$.each(response,function(index, value){
alert("value " + value);
});
}
});
}
I can see the response always as null. I am not sure what is going wrong, but seems the coding part is correct. Am I doing some mistake in ajax call?
As clearly explained in this answer, you need to use the JSON plugin, that will serialize the entire action (or a single root object when needed). You don't need then to do the parsing yourself, just evaluate the name variable.
To send JSON from JSP to action instead you need to use the JSON Interceptor in your stack.
Ensure you have getters and setters for everything.
Your Name variable should be name, both in Java and in Javascript. Only the accessors / mutators should use the capitalized N (getName, setName).
If the error persists, check carefully console and logfiles for errors, with devMode set to true.
Since this comment has gone too far, I've turned it into an answer :)

How to make ajax get call for text to Java controller in Spring MVC?

I am expecting a BigDecimal.toString() value from Web call.
But i am not manage to configure it and getting either 404-Not found or 406.
Following is Spring MVC Code
#RequestMapping(value="get/myData", method = RequestMethod.GET, produces = MediaType.TEXT_PLAIN_VALUE)
#ResponseBody
public String getMyData(#ModelAttribute("user") User user,
#ModelAttribute("detailForm") DetailForm form)
{
//A web service called return big decimal and return that big decimal value toString
return "Value";
}
Following is calling code:
var convId = $("#" + $("body form:first").attr("id")).find('input[name="_CONV_ID"]').val();
blockUI: false,
dataType: 'text',
type: 'GET',
url: "get/myData.do",
data: { '_CONV_ID': convId},
success: function (data) {
// new dialog
alert(data);
},
error: function (result) {
alert("Error" + result);
}
Could anyone please help me in adjusting code. On button click, a value is getting return from web service which is of BigDecimal type
Trying reaching the url http://localhost:8080/your_application_name/get/myData. If you find 404 error there, you need to check your web.xml. Check the section of servlet-mapping part.

How to use POST parameters in Play Framework?

I'm trying to make a POST request using JavaScript routing. In the routes file:
POST /comments controllers.Clients.addComment(text: String, client: Int)
GET /assets/javascripts/routes controllers.Application.javascriptRoutes()
on page:
jsRoutes.controllers.Clients.addComment(args.text, #client.id).ajax(...);
But it creates the request
POST http://localhost:9000/comments?text=qwe&client=1 HTTP/1.1
How do I make it pass parameters in the POST body instead of a request string?
Tak a look at ajax() documentation - that is, such example:
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
});
As Play JavaScript route already defines url and request method (type), you need only to add data (of course you don't need to specify them as a params in brackets)
jsRoutes.controllers.Clients.addComment().ajax(
data: {
client: #client.id,
text: args.text
}
);
Also you can send a text only to given client (determined by the URL (it can be POST but PUT looks nicer :)):
PUT /comments/:client controllers.Clients.addComment(client: Int)
in the view:
jsRoutes.controllers.Clients.addComment(#client.id).ajax(
data: { text: args.text }
);
So it will perform PUT request to http://domain.tld/comments/123 and text will be available in the form() as it was sent with POST:
public static Result addComment(int client) {
String receivedText = form().bindFromRequest().get("text");
// save it to DB ...
return ok( "Added comment: "+ receivedText+ ". for client id: " + client);
}
As i don't quite understand the JsRoutes in Play, what i did was:
In my view:
var client = 1;
$.ajax({
type: "POST",
url: "/comments/" + client,
});
And in my routes, the call to the method:
GET /comments/:client controllers.Clients.addComment(client: Int)
This works letting the browser make the request like a normal ajax call to some URL defined in routes.

Need help getting this Spring 3/AJAX/JSON drop down population working

I am trying to do a Spring MVC 3 ajax call to populate a drop down from json serialized data.
The problem I am seeing is I am not sure what format of JSON Spring is returning for my list, and why.
The method which returns the Ajax data looks like this:
#RequestMapping(value="/getMyObjects", method=RequestMethod.POST)
#ResponseBody
public List<MyObject> getMyObjects () {
List<MyObject> myobjects = // populate list
return myobjects;
}
And as far as I understand that should be all I need to do, right?
In my app logs I see it is indeed converting the response to JSON, as follows:
2012-06-20 11:08:21,125 DEBUG (AbstractMessageConverterMethodProcessor.java:139) - Written [[MyObject [id=1376, name=Something test], MyObject [id=1234 name=More test]]] as "application/json;charset=UTF-8" using [org.springframework.http.converter.json.MappingJacksonHttpMessageConverter#d1b7e5]
But that JSON string looks odd to me, is that valid?
I was expecting stuff like [{ id : 1376, name="Something test"}, { id : 1234, name="More test"}]
On the client side when I get the response and do an alert I see it says its an array of objects like this: [Object object] [Object object] and I dont know how to deal with this data.
I try:
alert(data); -- gives the output I just described above
$(data).each(function() {
alert(this.id); // undefined!
});
How do I use this kind of JSON data or how do I convert it to something more manageable?
[Edit] Attaching my client side code with current alert responses I am trying:
$.ajax({
type : "POST",
url : "getMyObjects",
success : function(data) {
alert(data); // [Object object] [Object object]
alert(data.value); // Undefined
$(data).each(function() {
alert(this.id); // Undefined for each iteration
});
},
error : function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
Spring 3 provides integration with DWR(direct web remoting) which is very cool framwrork for AJAX calls. In DWR you can handle lists very easily just like in core java.
This is it! you should get the json format that you were expected. no more code (parser, formatting ) in necessary.
What you dont see is the actual json returned. well you try your url right away in the browser without calling it by ajax like http://yourdomain/yourservlet/getMyObjects you then will see your json as it is.
or else, use firfox with firebug, and you can see your ajac call (request & and response)
UPDATE
$.ajax({
url: "path/to/your/url",
cache: false,
async: false,
success: function(data){
for (var i = 0; i < data.length; i++) {
alert(data[i].id);
alert(data[i].name);
}
}
});

Categories

Resources