How to pass array from java to javascript - java

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>

Related

Servlet not forwarding attributes to JSP (JSP receives null)

Servlet
ArrayList<String[]> itemsInCart = new ArrayList<String[]>();
String[] test = {"bah","3.50","false"};
itemsInCart.add(test);
ArrayList<Integer> testALEmpty = new ArrayList<>();
ArrayList<Integer> testALItems = new ArrayList<>();
testALItems.add(1);
testALItems.add(2);
testALItems.add(3);
String testStr = "This is a test string";
request.setAttribute("testALEmpty", testALEmpty);
request.setAttribute("testALItems", testALItems);
request.setAttribute("testStr", testStr);
request.setAttribute("cartAttribute", itemsInCart);
try {
getServletContext().getRequestDispatcher("/Cart.jsp").forward(request, response);
} catch (Exception e) {
e.printStackTrace();
}
JSP
if (request.getAttribute("cartAttribute") == null) {
%>
<b>No Cart</b>
<%
}
When the servlet forwards to the JSP, I have No Cart because for some reason the servlet is not passing the attributes to the JSP.
set request attribute to session attribute:
request.getSession().setAttribute("parameter", "test");
or
There are two ways you can accomplish this.
Using a JSP expression you would use <%= %> as (notice no ; at the end)
<%= parameter %>
The second and preferred way is to use JSP EL syntax and reference the request attribute directly using ${ } as
${parameter}
The first option requires you to pull the attribute out of its scope first. The second doesn't.
String parameter = (String) request.getAttribute("parameter");

How not to include special characters & numeric in Jquery TagIt

How can i show the special characters(~!##...etc) and numeric number(0-9) not in tag when user key in the value from the input tag? Is it possible to restrict special characters and numeric display in normal text? Any help would be appreciated.
Current output :
<%
ArrayList alTag = new ArrayList();
Vector vTag = new Vector();
String SQL = "SELECT CODE, DESCP FROM TB_FRUIT WITH UR";
TEST.makeConnection();
TEST.executeQuery(SQL);
while(TEST.getNextQuery())
{
Vector vRow = new Vector();
ArrayList alInner = new ArrayList();
String field =TEST.getColumnString("CODE");
String descp =TEST.getColumnString("DESCP");
alInner.add(field);
alInner.add(descp);
alTag.add(alInner);
vTag.addElement(field);
}
TEST.takeDown();
%>
<script>
var dbArray = [<%
String dbCode = "";
String dbList = "";
for(int i=0;i<vTag.size();i++)
{
dbCode = (String) vTag.elementAt(i);
dbList += "\"" + dbCode + "\",";
}
out.print(dbList); %>
];
$(document).ready(function() {
$("#myTags").tagit({
availableTags: dbArray
});
});
</script>
<html>
<body>
<input type="text" id="myTags" name="TYPE">
</body>
</html>
This restricts the input only to alphabets
$('#myTags').keypress(function (event) {
var regex = new RegExp("^[a-zA-Z]+$");
var str = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(str)) {
e.preventDefault();
return false;
}
});
If you are open to introducing a jquery plugin, the easiset way is to include the [alphanum jquery plugin] and then do
$('#myTags').alpha();
[alphanum jquery plugin] : https://github.com/KevinSheedy/jquery.alphanum
UPDATED :
You could extent the jquery tagit plugin and override the cleaned input method as shown below so as to replace non alphabets .
$.widget( "ui.tagit", $.ui.tagit, {
_cleanedInput: function() {
var cleanedInput = this.tagInput.val().replace(/[^a-zA-Z0-9\s]+/,"");
return $.trim(cleanedInput.replace(/^"(.*)"$/, '$1'));
}
});

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 java-script array into JAVA array using AJAX

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]+ ...

getParameter only returning part of the string

Kindly assist here, the getParameter is only printing the first portion of the String element in the tag.
here is the select tag
<select name="ActionSelect" id="ActionSelect" >
<%Iterator itr;%>
<% List data = (List) request.getAttribute("data");
for (itr = data.iterator(); itr.hasNext();) {
String value = (String) itr.next();
%>
<option value=<%=value%>><%=value%></option>
<%}%>
</select>
and here is the code in the servlet
PrintWriter pw = response.getWriter();
String connectionURL = "jdbc:mysql://localhost/db";
Connection connection;
try{
this.ibrand = request.getParameter("ActionSelect");
pw.println(ibrand);
} catch (Exception e) {
pw.println(e);
}
Use double quotes around value in the option tag:
<option value="<%=value%>"><%=value%></option>
As it is right now, you probably have a space in your value so only the part of the value before space is returned.
Incidentally, it's not necessary to declare the Iterator uptop; you can do so directly in the for loop:
for (Iterator itr = data.iterator(); itr.hasNext();) {
Finally, consider using tag libraries instead of writing java code directly as scriptlets in your JSP.

Categories