JAVA: get array sent from ajax/jQuery

[FONT=Verdana]
still having a hard time with this…

trying to go from here:
http://stackoverflow.com/questions/13241668/how-to-send-array-to-servlet-using-jquery-ajax

am trying with code in last response on this page… and of course the last question here, by OP, remains unanswered… namely, what to put in Java server side?

what I’m doing in Java (also from this SO example)

String[] myJsonData = request.getParameterValues("json[]");
out.println(myJsonData);

or rather, I’d say…


for (int i=0; i < myJsonData.length; i++) {
		out.println(myJsonData[i] + "<br>"); 
	}

is not working… result prints “fail”…

would appreciate some help…

thank you…

[/FONT]

1 Like

[FONT=Verdana]my jQuery/ajax code (again, following example in above SO url):


	var array = [ 1, 2, 3, 4 ];
	
	var json = JSON.stringify(array);
	
	
	$.ajax({ url:"testArrFour.jsp",
          type:"POST",
          data: json,
          dataType:'json',
         success:function(data){
				$("#output").append( data );
			//	window.location = 'testArrFour.jsp';
			},
			error: function() {
				 $("#output").html("fail"); 
			}
	});
		  

[/FONT]

[FONT=Verdana]it seems the options here are mainly:

whether to send data thus:

data:json,

or thus:

data: {json:json},

and whether to get array in back-end thus:

String[] myJsonData = request.getParameterValues("json");

or thus:

String[] myJsonData = request.getParameterValues("json[COLOR="#FF0000"][][/COLOR]");

and:

whether to do, in JavaScript, this,


	var json=[1,2,3,4];

or this


var array = [ 1, 2, 3, 4 ];
var json = JSON.stringify(array);

but no combination of these options is working for me…

[/FONT]

[FONT=Verdana]
still no answer???

:frowning:

[/FONT]

error: function() {
   $("#output").html("fail"); 
}

It’s printing “fail” because the ajax call is failing. You need to inspect the response with your browser inspector. Here is how to inspect the response through Chrome. I don’t remember how to do it in Firefox.

You should be able to see the exact page in a mini browser at the bottom of your screen. Alternatively, you can change it to a GET request instead of POST and just type it in the URL and load the page like a normal web page.

[FONT=Verdana]thank you for your responses, mawburn… yes I did see your last post on other thread… one of my problems is I have limited access to the internet now… and yes of course you’re right, of course, if it’s an array, have to print with a loop… that error I corrected a long time ago…:wink:

and well, I just don’t get what I’m missing here…
I have a test to send just a string, it works fine…
code:
JS (inside test.html):


var myStr = "this is a test, send single string with ajax/jQuery - this works";
	console.log(myStr);  // prints what I expect
	
	queryStr = '?stringToSend=' + myStr;

	$.ajax({
		url:"testString.jsp" + queryStr,
		type:"POST",
		success:function(data){
			$("#output").append( data );
		},
		error: function() {
			$("#output").append("fail");
		}
	
	});
	

on back-end/java:

String fromReq = request.getParameter("stringToSend");
out.println(fromReq);

works fine… string prints when I run test.html

for sending array, however, I run into weird problems:

JS (inside test_array.html):


var json = ["red","blue","green","yellow"];

	console.log(json);
	
	
	$.ajax({
		url:"testArrFourA.jsp",
		type:"POST",
		dataType:'json',
		data: {json:json},
		success:function(data){
			alert(data);
			$("#output").append( data );
		},
		error: function() {
			console.log('fail');   // doesn't print....
			console.log(typeof data); // prints 'undefined'
			$("#output").append('fail');
		}
	
	});
	

back-end/java:


String[] myJsonData = request.getParameterValues("json[]");

	for (int i=0; i < myJsonData.length; ++i) {
		out.println(myJsonData[i] + " --<br>");
	}
	

test_array.html doesn’t print “fail”, it prints nothing…

(and yes, I do need ‘’ in the java (‘json’), otherwise: 1) I get a 500 error on JSP, and: then browser prints ‘fail’…)

however:

when I inspect with firebug, and look in console, and click on little triangle to the left of jsp url, then click on “response” tab, it shows exactly what it should!!! I see entire HTML generated by testArray.jsp (complete with <html>, <head>, and <body> elements, and inside <body> it prints exactly what it’s supposed to, namely:

red –<br>
blue –<br>
green –<br>
yellow –<br>

I just don’t know why it doesn’t print on the browser when I run test_array.html on the browser… can’t see what I’m missing… maybe it has to do with this:

when I run test_array.html in the browser, firebug switches to “script” tab on its own, and it shows this:

JSON.parse: unexpected character 

(but still, it prints the result fine in “response” tab in firebug, and not in browser…[???] what on earth am I missing???)

thank you…

[/FONT]

Oh.

You’re not returning JSON. You’re returning HTML.


$.ajax({
   url:"testArrFourA.jsp",
   type:"POST",
   //dataType:'json',
   data: {json:json},
   success:function(data){
         alert(data);
         $("#output").append( data );
   },
   error: function() {
        console.log('fail');
        console.log(typeof data); // prints 'undefined'
        $("#output").append('fail'); 
   }	
});

jQuery is trying to parse the response as JSON, but it’s just HTML.

[FONT=Verdana]

thank you mawburn… so what am I doing wrong in my jQuery ajax code? please enlighten me…:wink:
(don’t get why json is need at all here… (but that’s what I gathered from searching online about this…)
it’s just a simple array of strings, just like when you post data from a form… you don’t need json to send the data then, do ya…:wink:

I had also tried:


var array = ["red","blue","green","yellow"];
var json = JSON.stringify(array);

only difference was result in “response” tab printed this:

[“red”,“blue”,“green”,“yellow”] –<br>

instead of what it printed when I just used


var json = ["red","blue","green","yellow"];

thank you…

[/FONT]

You’re sending JSON. You’re receiving HTML, not JSON data. JSON is a specific format. The rest of the “json” in your code is just variable names and doesn’t mean anything. It could read “bob” instead.


var bob = ["red","blue","green","yellow"];
console.log(bob);

$.ajax({
   url:"testArrFourA.jsp",
   type:"POST",
   data: {bob:bob},
   success:function(data){
         alert(data);
         $("#output").append( data );
   },
   error: function() {
        console.log('fail');
        console.log(typeof data); // prints 'undefined'
        $("#output").append('fail'); 
   }	
});

String[] myJsonData = request.getParameterValues("bob[]");
for (int i=0; i < myJsonData.length; ++i) {
   out.println(myJsonData[i] + " --<br>"); 
}

Alternatively, since you’re just returning HTML you could just do this:


var bob = ["red","blue","green","yellow"];
console.log(bob);

$("#output").load("testArrFourA.jsp", { "bob[]": bob});

Which is just a shortcut method for $.ajax in jQuery. The documentation is here: http://api.jquery.com/load/

Should work, I didn’t test it so no guarantees.

ok… thank you mawburn… that finally worked…

I never wanted to use JSON to begin with, but when I looked this up, most solutions suggested you had to use JSON
(I never thought JSON would be necessary for a simple array of strings…)

thank you very much…

(PS: I don’t like how either FF or Chrome print returns… they print the result like in an alert, you have to click ‘ok’ button to see result actually printed on browser page… what’s with that? had never seen that before… I don’t like it at all… is there a way around it? it doesn’t happen when I test with a simple string instead of an array of strings… [???] )

thanks again…

oh brother… now I’m getting a real weird error now in my one-string example… very very weird…

namely this:
http://stackoverflow.com/questions/10744110/error-with-appendchild-node-cannot-be-inserted-at-the-specified-point-in-the-hi?rq=1

had never ever seen this…

if, inside this fn success:function(data){, I print result only in console.log(), it prints fine… but if I do the typical

$("#output").append( data );

then I get that very weird error… oh brother…:frowning:
(was not getting this yesterday… same code…)

thank you again for all your help, mawburn…

(PS: I just realized my previous response got posted twice… sorry… this has to do w/my messed-up net connection…)

That’s unfortunate. JSON is how data is represented in Javascript. It’s amazing. I use JSON for a lot of different things. I believe that many of the NoSQL Databases are based around JSON, to what degree I don’t know I haven’t worked with them.

Whenever I have to pass data as strings, I use JSON whether it’s read by Javascript or not.

I’m not sure what you mean by this.

As far as your other error, be sure you’re using the correct div id.

<div id="output"></div>

[FONT=Verdana]
attaching screenshots of both FF and Chrome… (the one that looks the most like a standard alert (white bg) is Chrome… the one with gray bg is FF…

after I click ok, on both, the result prints on browser window (i.e., on web page) in standard fashion…)

thank you again for all your help…

(PS: on other issue, was getting that weird error because wasn’t loading page thru “localhost:8080/…” url but just using standard path-to-file address… duh… I’m a jerk…:wink:

still puzzled about other issue though (the way Chrome & FF display ajax results… had really never seen that… and I am loading that one (array test) the correct way…)

[/FONT]

I hate to say this, but I honestly have no idea what is happening there.

You don’t need all the extra tags in your result though. You just need the data. You can omit the <html><head> blah blah blah, except for the printout. I doubt this has anything to do with your issue.

ok… thank you again mawburn… yes I know about the tags… was just being anal…:wink: in real life-situation everything will be different/a bit more complex anyway…