illegal arument exception in ajax call while passing js array object - java

I am passing two variables in ajax call, one as normal string variable and other one js array object which i m sending to my java class..but when i m sending with array object,the ajax call is getting failed and throwing 500 response code with illegal argument exception
var array1 = new Array();
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
array1.push($(inputs[i]).attr('name').toString());
}
var path = "javaclassurl";
$.ajax({
type: "POST",
url: path,
data: {
var1: var1,
array1: array1
},
});
$(this).dialog("close");
//}
},
This is the way i m receiving in my java class
String values[]=request.getParameterValues("array1");
This ajax call is inside dialog box as its a dialog box plugin being used.Please help me in getting the error corrected

Could you please try doing it this way:
String values[]=request.getParameterValues("array1[]");

jQuery API documentation for .ajax() call states:
processData (default: true)
Type: Boolean
By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false.
So you might try setting this to false.

Related

Spring MVC Ajax: Passing Empty Array to Ajax Controller

I have the following which works well in receiving a non-empty Array,
$.ajax({
url: "ajaxController",
dataType: "json",
type: "get",
data: {
'term': request.term,
'exclude': ["45","66"]
},
Controller (note the [] in RequestParam Value -- the result goes in a String[]):
public List<KeyValueBean> getChoices(String term,
#RequestParam(value = "exclude[]")
String[] exclude) {
}
But if I pass an empty array in the same code, which sometimes happens, it breaks:
'exclude': []
or alternatively
'exclude': JSON.stringify([])
Error:
org.springframework.web.bind.MissingServletRequestParameterException: Required
String[] parameter 'exclude[]' is not present
If you pay attention to the error, it says your request parameter exclude can not be null. If you need to can send empty array sometimes, you can mark your parameter as optional(not required) in this way:
#RequestParam(required = false, value = "exclude[]")
The problem is probably because you passed your #RequestParam with value="exclude[]" while you are passing the object named as "exclude".
So, it actually should be:
public List<KeyValueBean> getChoices(String term,
#RequestParam(value = "exclude")
String[] exclude) {
}

how to extract array from java to ajax

I get the values from database to time array as follow
int[] time=Manager.playTime() ;
responsedata.put("status", "success");
responsedata.put("play", time);
And i am sending this time array to ajax in javascript file as follow
success:function(response){
$('body').css('cursor', 'default');
if(response.status == 'success'){
for( var i=0;i<response.play.length;i++){
alert("playtime---"+response.play[i]);
}
but here i am not getting the values from array .Please help me
Thanks
You responsedata seems to be a Java Map.
Try to use this in your success function
success:function(response){
$('body').css('cursor', 'default');
if(response.status == 'success'){
$.each(response.play, function (value) {
alert("playtime---"+value);
});
}
}
In your ajax you are getting whole object in response i.e. response.
You can get your play object by response i.e. response.play.
now iterate the the values from play object.
for (var i = 0; i < response.play.length; i++) {
//iterate your values here
alert(response.play[i].object_key);
//object_key is temparary name of your play object so give a proper key here.
}

Passing javascript array to servlet

I have looked previous questions on this topic on SO, but my problem is not solved yet.
I am passing the array from javascript to servlet.
JavaScript Code:
var action = new Array();
function getProtAcionValues(rowNo,columnCount)
{
for(var j=0;j<columnCount;j++)
{
action[j] = document.getElementById('textActions'+rowNo+''+j).value;
alert(action[j]);
}
}
Servlet Code:
String actions[] = request.getParameterValues("action[]");
if(actions!=null)
for(int i=0;i<actions.length;i++)
{
System.out.print(" Action: "+actions);
}
else
System.out.println("Action is null");
Using above code I am getting message "Action is null".
And if I try
String actions[] = request.getParameterNames("action[]");
I am getting Syntax error:
The method getParameterNames() in the type ServletRequest is not applicable for the arguments (String)
Please let me know if there is something wrong in code.
you can just simply get the array with the name of the array...
String actions[] = request.getParameterValues("action");
You can't pass a java array as a parameter, as it is an structure. The best way is to serialize it into an string object like a jSon. You can use JSON.stringify. Simple and efficient. As you can serialize in the server also, it's very useful.
Pass Javascript array variable with form action to send values to servlet, and then use
String[] darray=request.getParameterValues("variable name used with link");

Passing String from JSNI to Java - GWT

I am having problem passing String to a Java method in my GWT project:
public final native String waveIt()/*-{
var instance = this;
var data = $wnd.Waverecorder.data();
var strData = data.toString();
var arr = strData.split(',');
for (var i = 0; i < arr.length; i++) {
var data = arr[i];
console.log(data);
instance.#com.mycode.wave.showcase.client.Showcase::updateWave(Ljava/lang/String;)(data.toString());
}
}-*/;
Looking from the console log of Chrome/Firefox I can see that I get the right data (this is the exact log I get):
-0.00006103515625
-0.00006103515625
-0.00006103515625
-0.05072021484375
-0.553833007812
(more data omitted)
When the GWT java method received the data it is empty. What could be the reason?
This method should be void, because you do not return a string - you call a Java method from it.
Looking at your code, you don't need var instance = this; and you can remove instance. before #com.
You declare var data twice: before the loop and inside the loop. Instead of calling your Java method with data.toString(), you can call it with arr[i].
What do you mean by:
When the GWT java method received the data it is empty.
Are you talking about the string that waveIt() should return?
The bug may be that there is no return statement in waveIt().

Problems passing data to jquery's getJSON() - Will not accept map

I am trying to serialize my form (JSP/Struts 1.1) and put it into an object or map or whatever jQuery's .getJSON() method needs. Here is my js code:
// This function makes an AJAX call, passing the entire form to the Action class
function ajaxCallWithForm(inputURL, formName, onReturnFunction)
{
var formAsMap = serializeForm(formName);
$.getJSON(inputURL, formAsMap, onReturnFunction);
}
function serializeForm(formName)
{
var obj = {};
var a = $('#'+formName).serializeArray();
$.each(a, function() {
if (obj[this.name] !== undefined) {
if (!obj[this.name].push) {
obj[this.name] = [obj[this.name]];
}
obj[this.name].push(this.value || '');
} else {
obj[this.name] = this.value || '';
}
});
return obj;
}
This results in a java.lang.IllegalArgumentException on the back end (something to do with the BeanUtils.populate servlet method).
If I set the 2nd of 3 parameters of my .getJSON() call to something like this, it works fine and the data shows up in the form object in my Java back end:
// This function makes an AJAX call, passing the entire form to the Action class
function ajaxCallWithForm(inputURL, formName, onReturnFunction)
{
$.getJSON(inputURL, {"vehicleKeyNum":12345,
"vehicleID":"12345",
"rand":Math.random()},
onReturnFunction);
}
I have also tried creating a string with the proper syntax that includes the data from the form and that results in the same thing. I may have my syntax wrong for that. At any rate, my main problem is that:
1) The .getJSON() method accepts, "A map or string that is sent to the server with the request." as its 2nd parameter (see http://api.jquery.com/jQuery.getJSON/)
2) I am passing what I think is a "map"
3) I am getting a java.lang.IllegalArgumentException and don't know where to go from here
If you want to submit a form to server, you can simply use jQuery's serialize() OR serializeArray() method.
$.getJSON(inputURL, $(formName).serialize(), onReturnFunction);
You should have the data returned by the serialize/serializeArray method populated in your form bean if the element names are matched right.
here is a working example of serialize method (copied from jQuery website)
java.lang.IllegalArgumentException from the BeanUtils.populate servlet method is due to data type mismatch between the data submitted and the data on the form bean.

Categories