Appending JSTL ArrayList<String> to a Javascript String - javascript

I am trying to append a ArrayList to a JavaScript String variable using foreach loop but for some reason it doesn't seem to work. I have been trying to fix this problem for 2 days, but no luck yet. Can anyone help with this? Here's the code.
<div id="graphdiv"></div>
<script type="text/javascript">
var s = "";
<c:forEach items="${dateAndWaitTimes}" var="item">
s.append(${item});
</c:forEach>
g = new Dygraph(document.getElementById("graphdiv"), s);
</script>
Here dateAndWaitTimes contains the ArrayList of String, returned by the controller.
-
Output that I am getting:
Expected Output:

It seems you're getting array values correctly but nothing display correct.
one solution might be : put Java arraylist values into JS arrayList and then print JS arrayList values.
Code :
<script language="javascript">
$(function(){
var values = new Array();
<c:forEach var="item" items="${dateAndWaitTimes}" varStatus="status">
values.push("${item}");
</c:forEach>
alert(" VALUES => "+values[0]);
alert(" VALUES => "+values[1]);
//alert(" VALUES => "+values[2]);
});

Related

Converting object to string JQuery/JS/HTML

I am trying to append a list of countries to my select tag, but whatever I try it keeps showing as [object Object]. Here is my JS code:
I've tried var x = JSON.Stringify(country); and passing that into var o, and I've also tried country.toLocaleString('en-US); and that has not worked either. How can I have the countries show in the select list? Thanks
You need to use world_list[i].country to access country.
Here is demo code :
//your json
var report={"last_updated":"2020-06-02T04:15:21Z","regions":{"world":{"name":"World","totals":{"confirmed":6370499,"recovered":2904076,"deaths":377515,"critical":2811064,"tests":11709},"list":[{"country":"Hong Kong","confirmed":1088,"deaths":4,"recovered":1037,"Incidence_Rate":"14.49915619446103","Case-Fatality_Ratio":"0.36798528058877644","last_updated":"2020-06-02T04:15:21Z","country_code":"hk","daily_confirmed":0,"daily_deaths":0,"critical":47,"tests":5},{"country":"Macao","confirmed":45,"deaths":-1,"recovered":45,"Incidence_Rate":"6.930092308829553","Case-Fatality_Ratio":"0.0","last_updated":"2020-06-02T04:15:21Z","country_code":"mo","daily_confirmed":0,"daily_deaths":-1,"critical":0,"tests":-1}]}}};
var world_list = report.regions.world.list;
for(var i in world_list){
//use word_list[i].country to retrieve slected value
var o = new Option(world_list[i].country, i);
$("select").append(o);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
</select>

Reading array from java servlet in javascript

Hi like the title says I am trying to read an array from my java Servlet. I am trying to read the array in my java script file.
Java servlet code:
String graphData[] = dbHandler.select(attributes); // filling the array with data from database.
request.setAttribute("graphData", graphData);
RequestDispatcher dispatcher = request.getRequestDispatcher("/displayData.jsp");
dispatcher.forward(request, response);
<script type="text/javascript">
var graphData = ['${graphData}'];
var graphData= pageContext.getAttribute("graphData");
var graphData = document.getElementById("graphData");
var GraphData = ['${graphData}'];
log("test: " + graphData);
</script>
I tried all those options but none of them worked.
Can someone please tell me what the correct way is to read an array from a java servlet in a jsp page?
Thanks in advance!
edit:
what I can do is print out the data from the array on the JSP page (in the header) with this code:
<c:forEach items="${graphData}" var="temp">
<c:out value="${temp}"/><br />
</c:forEach>
But I want to use the data from the array in my JS code. which for some reason doesn't work.
You can use like this
<script>
var graphData = [
<c:forEach items="${graphData}" var="graph">
'<c:out value="${graph}" />',
</c:forEach>
];
console.log(graphData);
</script>

Compare variable values in scriplet and javascript

I have a jsp file with a scriptlet tag, I am getting the values of .properties file in it .I have a java script tag in which I am storing the value from the dropdown in a variable. On selecting some value in the dropdown I want to compare it with the property in the scriptlet and if it is equal a value from properties file must populate in my textbox. I have tried the following code but it is not working
My scriplet tag
<%
Properties prop = new Properties();
String propFileName = "server. properties";
InputStream inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);
if (inputStream != null) {
prop.load(inputStream);
} else {
throw new FileNotFoundException("property file '" + propFileName + "'not found in the classpath");
}
String appName = prop.getProperty("Demo_name");
String link = prop.getProperty("Demo_Links");
String database = prop.getProperty("DemoApps_DataBase");
%>
JavaScript
<script type="text/javascript">
function OnSelectionChange(serverName) {
var selectedOption = serverName.options[serverName.selectedIndex];
var txtbox=document.getElementById('serverLink');
var appName=<%=appName%>;
var links=<%=link%>
alert(appName.value);
if(selectedOption.value==appName.value){
txtbox.value=links.value;
}
}
</script>
Try this code. Is Your selected value is case sensitive?
<script type="text/javascript">
function OnSelectionChange(serverName) {
var selectedOption = serverName.options[serverName.selectedIndex].value;
var txtbox=document.getElementById('serverLink');
var demoName='<%=demoServer%>';
var testName='<%=testingServer%>';
var PNGName='<%=pngServer%>';
var DCPName='<%=dcpServer%>';
var demoLink='<%=demoLink%>';
var testLink='<%=testingLink%>';
var pngLink='<%=pngLink%>';
var dcpLink='<%=dcpLink%>';
if(selectedOption==appName){
txtbox.value=links;
}
if(selectedOption==PNGName){
txtbox.value=pngLink;
}
if(selectedOption==DCPName){
txtbox.value=dcpLink;
}
if(selectedOption==demoName){
txtbox.value=demoLink;
}
}
</script>
Using scriplets populate the values in a hidden field from your scriplet like :
<input id=hiddenPops type="hidden" name="Language" value="English">prop1=value2;prop2=value3</input>
In your javascript get the value of the above field using getElementById(hiddenPops )
Split the value string into array or as desired and you can work with it to match the keys and fetch the corresponding values.
Note: Its a solution but your approach is not great. Try to use modern JS frameworks which could allow you to talk to the server directly or simply use Ajax

Get servlet context in javascript

In my jsp I use <%String base = (String)application.getAttribute("base");%>
I tried to use 'base' in javascript but not work. Below is my javascript:
<script>
var newBase = <%=base%>;
</script>
Can anyone help me to solve this?Thanks
This is the eplanation www.w3schools.com give for location object property pathname:
pathname: Sets or returns the path name of a URL
In our case the javascript file wich is in your context.
The first element is that pathname is the context
So you split the attribute (see the split method in javascript String) and return it.
This should do.
<script language='javascript'>
function servletContext() {
var sc = window.location.pathname.split( '/' );
return "/"+sc[1];
}
</script>
You can rather try it out like this ,
set the value to the hidden field ,
input type="hidden" id="hidVal" name="txt2" value="${base}"/>
And in your java script ,
<script>
var x = document.getElementById('hidVal').value;
alert(x);
</script>
Update :
var newBase = '<%=base%>';
You are missing the quotes to treat the value as string .
Hope this helps !!

Javascript and variable scope

I have the need to create a two dimensional array to collect values in my jsp. In order to populate the 2-d array I'm using code like this
<script language="JavaScript">
var row = 0;
var multiDimenArray = new Array();
</script>
<c:forEach var="items" items="${item}" varStatus="status">
............
<script language="JavaScript">
multiDimenArray [row] = new Array();
var column = 0;
row++;
</script>
<c:forEach var="nestedItems" items="${nestedItem}" varStatus="status">
............
<script language="JavaScript">
multiDimenArray [row][column] = "some value";
column++;
</script>
However in the third script block when i attempt to assign the value i get a JS error saying that the variable row is undefined. Is it possible to pass variables between script blocks like this in JS?
You are getting that because you are incrementing row before the third script runs.
So when you try to run multiDimenArray [row][column] = "some value"; row actually equals 1 instead of 0.
You need to move the row++ to after the column is assigned.

Categories