Use a complex java map in a jquery function - java

In a .jsp page I have a complex java map, like this:
Map<UserDefinedType, Map<String, Boolean>> allMaps= (Map)request.getAttribute("allMaps");
I need to use this map in a jquery function. Is there any way to achieve this?
The jquery function looks like this:
$('#selectMenuId').click(function(){
var val =$('#selectMenuId').val();
var allMaps= <%= allMaps%>
// Is there any way to access all the keys and values of this allMaps variable?
});

Related

How to compare hash map key dynamically inside the closure in Grails?

Here I have hash map passed from the controller to GSP page.
Controller:
Map<String, List<String>> nameFiles = new HashMap<String, List<String>>();
nameFiles.put('patient1',["AA","BB","CC"]);
nameFiles.put('patient2',["DD","EE","FF"]);
model.put("nameFiles", nameFiles);
GSP page:
var patient = getPatient(); // lets say we get random patient through some jQuery function, could be not available in the nameFiles key
//check If nameFiles contain key same as patient varaible
<% nameFiles.each { fm -> %>
<% if (fm.containsKey(patient)) { %> // This if statement cannot compare dynamic sting varaaible. How to do this.
alert("Yes nameFiles contain the patient");
<% } %>
<% } %>
Assuming you have :
Map<String, List<String>> nameFiles = new HashMap<String, List<String>>();
nameFiles.put('patient1',[id:1,name:'Fred'])
nameFiles.put('patient2',[id:2,name:'Tom'])
It is as simple as this to get current patient:
<% def aa = nameFiles?.find{it.key=='patient1'}?.value %>
<g:if test="${aa}">
// we definitely have ${aa} and it has been made null safe
<g:if>
This returns {id:1, Name:Fred} on gsp which is the list iteration
My goodness all that else if it is as if you are in a controller, I understand why you are having to do this but it isn't good practice you could just create a tagLib that takes current value and processes the entry according to something in a given list or maybe against db fresh on the fly all correctly presented produced.
Final edit whilst you can declare variables like jsp you can also use
<g:set var="aa" value="${nameFiles?.find{it.key=='patient1'}?.value}" scope="page|session|..."/>
By default variable is set for the page but could be made into a session variable either way it is a lot cleaner than <% %>
Hopefully final edit
I think people should think carefully about what their actual problem is and try to present the problem clearly otherwise the audience ends up answering something else due to the poor quality of the post.
If I understand correctly you have something happening in a controller as in some list being produced. The missing bit must be you are then doing some form of form check maybe a select box selection that then ends up in jquery by that you mean you have some form of java script check going on against a form field check.
There are two ways of pumping such information into the javascript world for such purposes
Method 1:
//I haven't tested this, hopefully gives you the idea
var array = []
<g:each in="${namedFiles}" var="${pa}">
array.push({code:'${pa.key} listing:'${pa.value}'})
</g:each>
Method 2
Controller
//where you now push named files as a json
return [namedFiles as JSON].toString()
// or alternatively in gsp javascript segment something like this
var results=$.parseJSON('<%=namedFiles.encodeAsJSON()%>');
var results = results['patient1']
Honestly speaking I didn't get what are you asking and what kind of problem do you have as a result, but I guess that you tried to implement something like that:
<g:if test="${nameFiles[patient]}">
alert("Yes nameFiles contain the patient");
</g:if>
As you may be noticed I tried to avoid the scriptlet mess and used grails custom tags.
Also I hardly imagine how are you going to call the jQuery function to get a variable and then use it for generating a view on the server side. But try to define some mock "patient" variable at first to test my sample.
If the "patient" variable value is only available at the client side - so you have to change the approach and generate your alerts not on the server.
UPD
From the other hand you could return your nameFiles as JSON in your controller and then parse this JSON with javascript on the client side like that:
var nameFiles = JSON.parse("${nameFiles}")
if (nameFiles.hasOwnProperty(patient)) {
alert("Yes nameFiles contain the patient");
}
I haven't test this code, but at least you are pointed that gsp are rendered on server and you can convert your map to JSON, pass it to the view, parse with JavaScript and generate the needed alert.
Variable Declaration in GSP
You can declare variables within <% %> brackets:
<% patientIdentifier = 'randomName' %>
For more details see the Grails documentation on Variables and Scopes.
Checking if Patient is contained in namedFiles
You don't need to iterate over the map. Just checking the map if it contains the key.
// check if nameFiles contains key same as patient variable
<% if (nameFiles.containsKey(patient)) { %>
alert("Yes nameFiles contains the patient");
<% } %>

Replace equal with semicolon in Java Script Object

I am sending the Map<String,String> object from servlet to jsp whose key is attribute name and value jsonvalue. My Requirement is to collect the value of key in variable that is root here. But when I tried to assign these map object to JavaScript variable i'ts throwing an error because the map object contains the = operator in the data. So to remove the error I assigned = with : manually its working fine.
So please tell me how do I remove the = with : with JavaScript code? Or is there any way to send the data with semicolon from servlet?
The data is coming in this format:
var trees= {dage={"nodeId":3,"value":"0-7","children":[{"nodeId":2,"value":"4-7","children":[{"nodeId":1,"value":"6-7","children":[{"nodeId":0,"value":"7","children":[]},{"nodeId":4,"value":"6","children":[]}]},{"nodeId":6,"value":"4-5","children":[{"nodeId":5,"value":"5","children":[]},{"nodeId":7,"value":"4","children":[]}]}]},{"nodeId":10,"value":"0-3","children":[{"nodeId":9,"value":"2-3","children":[{"nodeId":8,"value":"3","children":[]},{"nodeId":11,"value":"2","children":[]}]},{"nodeId":13,"value":"0-1","children":[{"nodeId":12,"value":"1","children":[]},{"nodeId":14,"value":"0","children":[]}]}]}]},
dpob={"nodeId":6,"value":"4;3;5;6;1;2;0","children":[{"nodeId":5,"value":"0","children":[{"nodeId":4,"value":"0","children":[{"nodeId":3,"value":"0","children":[{"nodeId":2,"value":"0","children":[{"nodeId":1,"value":"0","children":[{"nodeId":0,"value":"0","children":[]}]}]}]}]}]},{"nodeId":12,"value":"4;3;5;6;1;2","children":[{"nodeId":11,"value":"3;5;6;1;2","children":[{"nodeId":10,"value":"5;6;1;2","children":[{"nodeId":9,"value":"2","children":[{"nodeId":8,"value":"2","children":[{"nodeId":7,"value":"2","children":[]}]}]},{"nodeId":15,"value":"5;6;1","children":[{"nodeId":14,"value":"1","children":[{"nodeId":13,"value":"1","children":[]}]},{"nodeId":17,"value":"5;6","children":[{"nodeId":16,"value":"6","children":[]},{"nodeId":18,"value":"5","children":[]}]}]}]},{"nodeId":22,"value":"3","children":[{"nodeId":21,"value":"3","children":[{"nodeId":20,"value":"3","children":[{"nodeId":19,"value":"3","children":[]}]}]}]}]},{"nodeId":27,"value":"4","children":[{"nodeId":26,"value":"4","children":[{"nodeId":25,"value":"4","children":[{"nodeId":24,"value":"4","children":[{"nodeId":23,"value":"4","children":[]}]}]}]}]}]}]}}
I am trying to iterate this map working fine if : is there to get the key.
for (var key in trees){
if(key===attribute_name){
root=trees[key];
break;
}
}
This is the jsp code through which i am getting the data
<script type="text/javascript">
var treeStructure=<%=request.getAttribute("treeData")%>;
<script>
Convert your Map<String, String> into a JSON string using a JSON parse library. Then, set this data into a variable in your JavaScript code (after parsing it properly).
Here's an example using Jackson library.
Java servlet (or whatever controller you use) code:
Map<String, String> yourMap = ...;
//fill your map...
request.setAttribute("theMapAsJSON", new ObjectMapper().writeValueAsString(yourMap));
JavaScript code:
<script type="text/javascript">
var treeStructure = JSON.parse('${theMapAsJSON}'); //naive approach
<script>

Interaction between JSP and External javascript files

I am newbie to external javascript files (*.js). Basically I have my JSP ready but my manager wants me to add graphics in it.
So I found some *.js files. But I don't know how to communicate between them and my JSP page.
I want to pass data from jsp to external .js file.
Is there any mechanism to do that?
For e.g:-
Demo.jsp
out.print(request.getAttribute("Name"));
Now I want use/pass/set above value to main.js file how to do that?
<script type="text/javascript">
var myJavascriptVariable = <%= request.getParameter("Name")%>;
//or .getAttribute("Name")
</script>
This could do the trick, it will make a global Variable which could be accessed in main.js. When you have GET Parameters you could also use only JS:
var paramarr = window.location.search.substr(1).split("&");
var params = {};
for (var i = 0; i < paramarr.length; i++) {
var tmparr = paramarr[i].split("=");
params[tmparr[0]] = tmparr[1];
}
or a bit shorter:
var params = {};
// parse URL's GET parameters and iterate over them
window.location.search.substr(1).split("&"),forEach(function(el) {
var kv = el.split('"'); // split into [ key, value ] array
params[kv[0]] = kv[1];
});
Now you can access the parameter in JS via:
params['name']
Personally I would use AJAX (e.g. with the help of JQuery) to get Data for my JavaScript files, you can look at that at http://api.jquery.com/category/ajax/shorthand-methods/ (2018 edit: kust use native ajax calls or whatever JS framework is hyped this week ;-) )
If you are using .js file you can't write jsp sriptlet in it.
If you need to call value in .js file there is one simple way.
Assign values to input elements in .jsp page.(If you are not using values in .jsp page assign values to hidden input elements)
Then include.js file in your .jsp page
get values as javasript or jquery methods.
Ex:-
value= document.getElementById("element_id").value
OR If you are using jquery you can get as
value = $("#element_id").val();
You can declare a global js variable and assign the value.
<% String myValue = (String)request.getAttribute("Name"); %>
var global1 ='<%= myValue %>';

How can I access Java list elements from my client-side JavaScript code?

I have the following simple script, which I am using to dynamically create the list elements in a <ul>
<script type="text/javascript">
function generate(){
var arr = new Array();
<c:forEach items="${articles}" var="a" varStatus="status">
$('#listitems').append(
"<li>"+${a.title}+"</li>"
);
arr[${status.index}] ="${a.slideShow.images}";
</c:forEach>
}
</script>
My problem stems from the images attribute. Every article has a slideshow and every slideshow has a list of images. I want to pull out the very first image from the list of images via the jave list.get(index); I want to do something like "${a.slideShow.images.get(0)}";. The get() is a java method from the list object.
Any ideas?
In EL you can use the brace notation to access a List element by index. Thus, the following should do:
arr[${status.index}] = "${a.slideShow.images[0]}";
This will behind the scenes do exactly as you proposed: a.getSlideShow().getImages().get(0).
That said, you normally declare JS arrays like follows:
var arr = [];
The new keyword is considered discouraged in JS.
As those who commented on your question suggest, this is a common misunderstanding. By the time your JavaScript executes (in the browser), Java and JSP and JSTL are no longer available. The JSTL/JSP execute at the server to create source/HTML that is then sent to the client.
View source on your page - it might shed some light. You should not see the JSP/JSTL you include above.

JSP, JavaScript, and Java Objects

I have a JSP where I'm using a javascript framework to build a chart using the Google Visualization API.
My servlet is returning a sales hashmap object with year as the key and integer (sales number) as the value.
My javascript uses the sales object to add data to the Google chart API which builds my chart.
code:
sales = '<%= session.getAttribute("sales") %>';
The sales object in my js gets the hashmap but it's a long string. Do I have to parse it in my javascript or is there a way it will automatically put the hashmap object properly into the javascript sales object?
you wont need to use an external json library (but you could!) - you can print out the json directly into a javascript variable like:
<%# taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<script>
(function(){
var sales = {
<c:forEach var="entry" items="${requestScope['sales'].entrySet}" varStatus="counter">
'${entry.key}' : ${entry.value} //outputs "2000" :1234 ,
<c:if test="${!counter.last}">, </c:test>
</c:foreach>
};
//js code that uses the sales object
doStuffWith(sales);
})()
</script>
Java and Javascript are completely different languages. Javascript doesn't know what do do with a Java HashMap object (actually in your example you'll get the output of HashMap.toString()). You'll have to serialize it into some form that Javascript will understand, eg. JSON.
Try using JSON which will allow you to describe your Java object in json ( java script object notation ) That way you can load the described object directly into javascript.
All this piece of code
sales = '<%= session.getAttribute("sales") %>';
does is print the value of session.getAttribute("sales") to the HTML output. Without any logic on your part as to how to format the output, Java will merely call .toString() on that Object - which the default implementation (unless you override it) usually results in an output that looks like classname#1234abc12.
So the short answer is that yes you will need to put in some logic on the Java side as far as how you would like your object / data structure to be output into the HTML document.

Categories

Resources