how to pass java-script array into JAVA array using AJAX - java

I am trying to post an array of JavaScript into an array of Strings in Java. It goes like this...
My JavaScript code:
var quantity_arr = new Array();
for (var i=0; i< <%= cart.size() %>; i++) {
quantity_arr[i] = document.getElementsByClassName("quantity")[i].value;
}
xmlhttp.send("sum_of_order="+sum_of_order+"&credits_number="+credits_no+"&credit_card_number="+credit_card_number+"&quantity_arr="+quantity_arr);
This is my Java code:
String[] myParams =new String[cart.size()];
String order_id=Integer.toString(temp);
String customer_id="'"+session.getAttribute("user_id")+"'";
String date= "15/29/12";
String sum=request.getParameter("sum_of_order");
String credit_card= "'"+request.getParameter("credit_card_number")+"'";
String credits="'"+request.getParameter("credits_number")+"'";
myParams = request.getParameterValues("quantity_arr");
All the params works fine except the myParams array that gets nothing. Can someone help me with this?

Try
String[] myParams = request.getParameterValues("quantity_arr").split(",");

Please see: http://support.dataweb.com/Help/default.view?Topic=Request.getParameterValues()
Basically, you cannot pass directly "quantity_arr="+quantity_arr but you have to use:
"quantity_arr="+quantity_arr[0]+"&quantity_arr="+quantity_arr[1]+"&quantity_arr="+quantity_arr[2]+ ...

Related

JSON stringify still returns [object Object] in JS

I have a little problem with stringify.
I am passing variable from Java to JavaScript.
In Java after out.println(strin); it looks like this:
[{"date":"01-18-2015"},{"date":"01-19-2015"},{"date":"01-21-2015"},{"date":"01-19-2015"},{"date":"01-19-2015"},{"date":"01-19-2015"}]
So I am trying to pass it to JavaScript
var obj = new String(<%= strin %>);
var tekst = JSON.stringify(obj);
alert(tekst);
But this alert still gives me [object Objetc],[object Object] etc.
However if I am putting that dates straightly to JS variable like this:
var zmienna = '[{"date":"01-18-2015"},{"date":"01-19-2015"},{"date":"01-21-2015"},{"date":"01-19-2015"},{"date":"01-19-2015"},{"date":"01-19-2015"}]';
stringify works good.
Im really confused about this. Can anyone give me some tips?
My code for json in Java looks like this:
String next_date = "";
JSONArray json = new JSONArray();
while (daty.next()) {
next_date = formatter.format(daty.getDate("date"));
JSONObject obj = new JSONObject();
obj.put("date", next_date);
json.put(obj);
}
String strin = json.toString();
It is the JSON notation (JavaScript Object Notation) that you taking advantage of.
When you declare a variable this way:
var zmienna = '[{"date":"01-18-2015"},{"date":"01-19-2015"},..];
you basically declare an array[] with elements that are objects{}.
It is equivalent to below code.
var firstDate = new Date("01-18-2015");
var secondDate =new Date("01-19-2015");
var zmienna = [firstDate, secondDate];
This is ready to use array, while in the other code you declare a String variable with some characters in it.
var obj = new String(<%= string %>);
I hope it clarified you understanding.

Passing multiple values from Servlet to JSP but I get only 1 value in JSP

I am trying to pass both latitude and longitude values from a Servlet to a JSP but I get only 1 value in the JSP
Servlet page
for(int i=0;i<json.length();i++)
{
String lat=json.getJSONObject(i).get("lat").toString();
String lon=json.getJSONObject(i).get("lon").toString();
lats[i]=lat;
lons[i]=lon;
request.setAttribute("lats", lats[i]);
request.setAttribute("lons", lons[i]);
System.out.println(lats[i]+","+lons[i]);
}
JSP page
var len=<%=request.getAttribute("len")%>;
lats[0]=<%=request.getAttribute("lats")%>;
<% String[] lats=(String[]) request.getAttribute("lats");%>
<% String[] lons=(String[]) request.getAttribute("lons");%>
for(i=0;i<len;i++)
{
var locations =[
['<%=request.getAttribute("cid")%>',lats,lon]
];
alert(locations);
}
Where am I going wrong?
As currently written, you overwrite the 2 request attributes (lats and lon) at each iteration. A request attribute is not a magic container, but the simple object last used in addAttribute. So in you JSP, you later only get the value of last lats and lon.
Assuming lats and lon and arrays in your code, you should write :
for(int i=0;i<json.length();i++)
{
String lat=json.getJSONObject(i).get("lat").toString();
String lon=json.getJSONObject(i).get("lon").toString();
lats[i]=lat;
lons[i]=lon;
System.out.println(lats[i]+","+lons[i]);
}
request.setAttribute("lats", lats);
request.setAttribute("lons", lons);
To put the arrays in the request attributes.
Then in the JSP ${lat} and ${lon} will refer to the arrays, and you can use ${lat[O]}, or ${lat[i]}, provided for last expression that i is a scoped variable containing a integer value less than array size.
You should pass Hashtable from servlet to JSP.
Servlet
HashMap latsMap = new HashMap();
HashMap lonMap = new HashMap();
for(int i=0;i<json.length();i++)
{
String lat=json.getJSONObject(i).get("lat").toString();
String lon=json.getJSONObject(i).get("lon").toString();
lats[i]=lat;
lons[i]=lon;
latsMap.put("lats"+i,lats[i]));
lonMap.put("lons"+i,lons[i]));
System.out.println(lats[i]+","+lons[i]);
}
//You can put these as Session attribute also
request.setAttribute("lats", latsMap);
request.setAttribute("lons", lonMap);
JSP
<% HashMap latsMap==(HashMap)request.getAttribute("lats");
HashMap lonMap=(HashMap)request.getAttribute("lons");
int len = latsMap.size();
for(int i=0;i<len;i++)
{
String lats = latsMap.get("lats"+i);
String lon= lonMap.get("lons"+i);
String locations ="[['"+request.getAttribute("cid")+"',"+lats+","+lon+"]]";
//If request.setAttribute("cid",<SomeValue>); is not present in servlet then
//remove request.getAttribute("cid") from JSP , Change it to
//String locations ="[,"+lats+","+lon+"]]";
out.println(locations);
}
%>
Try like follows:
for(int i=0;i<json.length();i++) {
String lat=json.getJSONObject(i).get("lat").toString();
String lon=json.getJSONObject(i).get("lon").toString();
lats[i]=lat;
lons[i]=lon;
System.out.println(lats[i]+","+lons[i]);
}
request.setAttribute("lats", lats[i]);
request.setAttribute("lons", lons[i]);
This is what i have done to store coordinates..
<% Integer len =(Integer)request.getAttribute("len");
int ilen =len.intValue();
String[][] locations =new String[ilen][3];%>
<% String[] lats=(String[]) request.getAttribute("lats");
String[] lons=(String[]) request.getAttribute("lons");
for(int i=0;i<ilen;i++)
{
System.out.println("i = "+i+", latlong= "+lats[i]+","+lons[i]);
locations[i][0] = (String) request.getAttribute("cid");
locations[i][1] = lats[i];
locations[i][2] = lons[i];
}
%>
with this can u provide me some help with the markers..

How to pass array from java to javascript

I want to pass a String Array From java to javascript. How can i acheive the same.
using loadUrl, i am passing the Java String [] to a javascript Function. (String[] StringName--> ["hello", "hi"])
But when i try to access the same in javascript
function displayString(StringName) {
for(var i=0;i<StringName.length;i++) {
alert("path : " + StringName[i]);
}
}
i am expecting length to be 2 as there are only 2 items in the Java String[].
But in javascript it is cominng as a String.
Whatformat i have to use to get it as an array
Two ideas come to my mind. You can create a javascript array using jsp or you can use a separator for the java array and create into a string, then read back in javascript using split() on the string.
Method 1:
<% String array[] = // is your initialized array %>
<script>
var jsArray = new Array();
<% for(String element:array){
%> jsArray[jsArray.length] = <% element %>
<% } %>
</script>
This should create a ready to use Javascript array with the values contained in your Java array.
Method 2: (Using separator as #)
<% StringBuilder sb = new StringBuilder();
for(String element:array){
sb.append(element + "#");
}
%>
<script>
var temp = <% sb.toString() %>
var array = temp.split('#');
...
</script>
Java to JSON and JSON to Java is fairly well covered ground.
you should check this out.
https://stackoverflow.com/questions/338586/a-better-java-json-library
<%
String[] jArray= new String[2];
jArray[0]="a";
jArray[1]="b";
StringBuilder sb = new StringBuilder();
for(int i=0;i<jArray.length;i++)
sb.append(jArray[i]+",");
%>
<script type="text/javascript">
temp="<%=sb.toString()%>";
var array = new Array();
array = temp.split(',','<%=jArray.length%>');
alert("array: "+array);
</script>

How to convert String to ArrayList

I need your help about retreive data from mysql db. I cant add string to array list.
my list declare
ArrayList<HandleListReport> reportList = new ArrayList<HandleListReport>();
here my code
report_data = json.getJSONArray(TAG_REPORT_DATA);
for (int i = 0; i < report_data.length(); i++) {
//storing variable
JSONObject c = report_data.getJSONObject(i);
String reportID = c.getString(TAG_REPORT_ID);
String userID = c.getString(TAG_UID);
String projectName = c.getString(TAG_PROJECT_NAME);
String localWork = c.getString(TAG_LOCATION);
String timeStart = c.getString(TAG_TIME_START);
String timeEnd = c.getString(TAG_TIME_END);
Log.d(TAG_LOCATION, localWork);
// add data to Arraylist
reportList.add(new HandleListReport(reportID, userID, projectName, localWork, timeStart, timeEnd));
my problem my listReport missing string data. Logcat show reportList ---> []
thanks for answer!
create a list of string
List<String> list ......
list.add(String)
then list.toArray() method
http://docs.oracle.com/javase/6/docs/api/java/util/List.html#toArray(T[])
it seems you are trying to store object of HandleListReport in arraylist. In that case use the following to initiate
ArrayList<HandleListReport> reportList = new ArrayList<HandleListReport>();
It seems that the length of variable report_data is 0, so the element does not add the list.

How i can get all the keys from a string which somehow looks like json string

I have a string like below
{"226167":"hawaiii","3193":"california"}
Can I use some java method to get all the key values (226167,3193 ) in a List object. If yes How it's done...?
String json = "{'226167':'hawaiii','3193':'california'}";
JSONObject object = (JSONObject) new JSONTokener(json).nextValue();
Iterator<String> yourKeys = object.keys();
for( String s : yourKeys)
System.out.println( s );
You need the JSON.Org library to run this (http://www.json.org/javadoc/org/json/JSONTokener.html)
Regards,
Stéphane

Categories