Javascript map from java map - javascript

I want to create a javascript map from a java map to set a dropdown value depending upon the value selected in another dropdown.
Below is the code(not working):
var categoryAndReportsMap = new Object();
<%
Map<String,Set<String>> categoryAndReportsJ = (Map<String,Set<String>>) request.getAttribute("categoryAndReports");
for(Map.Entry<String,Set<String>> e : categoryAndReportsJ.entrySet()){ %>
categoryAndReportsMap[ <% e.getKey(); %> ] = <% e.getValue(); %>;
<% } %>
Please suggest how can I achieve this.

You need quotes around the keys and values :
categoryAndReportsMap["<%= e.getKey() %>"] = "<%= e.getValue() %>";
But this supposes those strings don't contain quotes themselves. The best solution would be to use a JSON serializer like the excellent gson, this would be as simple as
var categoryAndReportsMap = <%= gson.toJson(categoryAndReportsJ) %>;

Related

Rails passing value to hidden field using javascript

I have an array structured as follows:
<% #locations = [['Town 1',2],['Town 2',2]...] %>
That I pass through an options_for_select tag that passes the shows the town name correctly and passes the id when submitted which is great. But, what I want to do is pass the town name (key?) as well to display on the results page as well. I understand the best method is to use a hidden_field_tag with javascript to pass the value through, but all I can pass is the id value, not the town name value.
Form
<%= form_tag(results_path, method: :post) do %>
<%= select_tag :location, options_for_select(#locations) %>
<%= hidden_field_tag(:location_name, value = nil, html_options = {id: 'locationName'}) %>
<%= submit_tag 'Submit' %>
<% end %>
Javascript
$('#location').change(function(){
var input = document.getElementById("location");
var site = document.getElementById("locationName");
site.value = input.value;
})
As you're using jquery:
$('#location').change(function(){
var locationName = $("#location option:selected").text(); # this will return the selected option text e.g. location name
$("#locationName").val(locationName);
})
Hope it works!

Using RegExp and eval() to replace a value

I need to use RegExp to replace a string and eval() to execute the object.
In my code below, I'm currently in a forEach of items.
item.url : http://localhost:3000/formation/[[item.id]]/[[item.launch_url]]
My code :
<% _.forEach(items, function(item) { %>
<% _.forEach(tableLineActions, function(tableLineAction) { %>
<% if (tableLineAction.conditionToShow) { %>
<% var label = tableLineAction.label; %>
<% var url = tableLineAction.url.replace(/\[\[item.id\]\]/g, item.id).replace('[[modelName]]', modelName).replace('[[item.seo_url]]', item.seo_url); %> // not reusable code
<% url = eval(url.replace(/\[\[/g, '').replace(/\]\]/g, '')); %> // test of a reusable code
<li><icon class="material-icons"><%=tableLineAction.icon%></icon><%=label%></li>
<% } %>
<% }); %>
<% }); %>
Error message : Invalid regular expression flags
I found a solution but this one is not maintenable if I want to send severals properties :
url = url.replace(/\[\[item.id\]\]/g, item.id).replace(/\[\[item.launch_url\]\]/g, item.launch_url)
With this solution, I need to add a new replace() method when a new property is sending and I want something more reusable without specifying all properties to replace.

How to store a mysql string in a javascript variable using jsp

I want to store mysql strings in a javascript array variable. I am using jsp for server-side.
I tried it in three ways. All the three aren't working. Need some help.
Attempt-1:
<script>
var name = [];
<%
st=con.prepareStatement("select name from company");
rs=st.executeQuery();
while(rs.next()){
String s = rs.getString(1);
%>
name.push(<%=s%>);
<%
}
%>
</script>
Attempt-2:
<script>
var name = [];
<%
st=con.prepareStatement("select name from company");
rs=st.executeQuery();
while(rs.next()){
%>
name.push(<%=rs.getString(1)%>);
<%
}
%>
</script>
Attempt-3:
<script>
var name = [];
<%
st=con.prepareStatement("select name from company");
rs=st.executeQuery();
while(rs.next()){
%>
name.push(<%out.print(rs.getString(1));%>);
<%
}
%>
</script>
All the three attempts showed the same result and error after processing.
Interpreted Code:
<script>
var name = [];
name.push(tcs);
name.push(wipro);
</script>
Error:
ReferenceError: tcs is not defined
You should add " around your string also you should javascript encode it(I think apache has a library that will do this for you):
<script>
var name = [];
<%
st=con.prepareStatement("select name from company");
rs=st.executeQuery();
while(rs.next()){
String s = StringEscapeUtils.escapeJavaScript(rs.getString(1));
%>
name.push("<%= s %>");
<%
}
%>
</script>
Try using this Apache library to escape the java string based on javascript rules: StringEscapeUtils
Javascript is trying to interpret name.push(tcs); tcs as a variable which in this case tcs has not been declared or initialized it is undefined. Instead you want javascript to interpret tcs as a string so you need quotes around it "tcs" or in your case "<%= s %>".

Using jQuery UI autocomplete plugin in Rails app

I'm interested in using the jQuery UI autocomplete plugin in my Rails app. The number of possible values will be small, so I wanted to store them client-side. So I have my controller set up as follows:
def index
#tags = Tag.find(:all).map { |t| t.name }
end
And in my view:
var tags = <%= #tags %>
The problem is that this renders as:
var tags = ["tag1","tag2"];
Instead of:
var tags = ["tag1","tag2"]
What do I need to do differently in order to stop escaping those quotes inside my tag array?
What about:
var tags = <%=raw #tags %>;
EDIT:
in your controller
#tags = Tag.find(:all).map(&:name).to_json
in your view:
var tags = <%= #tags %>;
It's the same as what you presented but you're sure it's valid and sure (because escaped) json (+ the query is improved).
I'm still questioning about the XSS + raw...
I was able to solve this by changing my view code to:
<%= array_or_string_for_javascript(#tags) %>
The thing missing in your controller is html_safe - here is an example:
controller
#keys = #categories.map { |x| x.name }
#autocomplete_categories = #keys.to_json.html_safe
view:
<script type="text/javascript">
$(document).ready(function() {
var data = <%= #autocomplete_categories %>;
$("#auto").autocomplete( { source: data } );
});
</script>

javascript in my .html.erb using embedded ruby--escaping problems

I'm trying to embed data I have defined in my controller in my view.
in view.html.erb:
<script>
some_var = <%= #var_data %>
some_ints = <%= #int_data %>
</script>
in my controller:
#var_data = ['hi', 'bye']
#int_data = [1,2,3,4]
however, when I view the generated html file, it looks like
<script>
some_var = ["hi", "bye"]
some_ints = [1,2,3,4]
</script>
ie the ints are fine but all the quotes got escaped. I tried
some_var = <%= #var_data.map {|i| i.html_safe} %>
instead but it didn't do anything (and also html_safe didn't work on the whole array). How should I do this?
Thanks
have you tried this?
<%=raw #var_data %>

Categories