Can I define a javascript variable to a grails object? - javascript

Can I assign a javascript variable to a grails object like this?
var newReport = ${report};
report is a grails domain object, which is passed back from controller to the gsp file.
Currently this doesn't work in my page.

Assuming that report is a Grails domain class, you will have to 'translate' this to a valid javascript format. One way is to set this as JSON. Something like:
In the controller
def reportJson = report as JSON
In the gsp
<script type='text/javascript'>
var newReport = $.parseJSON("${reportJson}");
</script>
The parseJSON takes the json string and return a javascript object.

Just render domain object as JSON to gsp, where some javascript code get the json by eval() function. For instance:
domain class - Band:
String bandName //some property
...
controller:
def bands = Band.list()
render(template:"result", model:[bands:bands as JSON]
_result.gsp:
<script>
var bandList = eval(${bands});
for(i=0; i<bandList.length; i++){
var name = bandList[i].bandName;
....
}
....
</script>

Related

Quarkus how to use javascript list string in template

I want to include javascript list string in template at quarkus app.
I define ConfigProperty like this.
#ConfigProperty(name = "my_list_string")
lateinit var myListStrings: List<String>
And I use this at template like this.
<script type="text/javascript">
var myListString = {myListStrings};
myJSFunc(myListString);
</script>
When I set my_list_string=test, output is below.
<script type="text/javascript">
var myListString = [test];
myJSFunc(myListString);
</script>
The myJSFunc needs list string, so I want to get ['test']
Also, I set my_list_string="'test'", the output is below.
<script type="text/javascript">
var myListString = ['test'];
myJSFunc(myListString);
</script>
If anyone know how to set JavaScript list string at quarkus app, please tell me about it.
Thank you.
Environment
Java 11
Quarkus 1.5.2
The #ConfigProperty happens on the server side (in Java).
You'll need to expose a REST method to get it the value of that property on the client side (in JavaScript).
Something like
#ConfigProperty(name = "my_list_string")
lateinit var myListStrings: List<String>
#Path("/my_list_string")
String getMyListString() {
return my_list_string;
}
And then retrieve that in your .js file, probably in the document is loaded event.

How to inject JavaScript variable in a Django template filter

I have a Django template filter to retrieve dictionary items based on the key passed.
{% with data=dict_data|get_data:key %}
I have separately made a template_tag.py file which returns those items.
def get_domain_data(dictionary, key):
p = ast.literal_eval(dictionary)
return p[key]
# data being returned successfully
The issue is in passing the dynamic value of the key in the filter function.
<script>
var key_val = $('#input_id').val();
'{% with data=dict_data|get_domain_data:"'+key_val+'" %}'; //encountering error here
// rest of the code
'{% endwith %}';
</script>
If I hardcode a string value the entire operation works, but I am unable to use the JavaScript variable within the Django {% filter %} function.
As mentionned by Matt Ellen in a comment, the template code is executed on the server, then the generated result is sent to the browser which interprets the javascript parts - so this just can not work this way.
If your data dict is small enough and doesn't depend on javascipt user interactions (ie the javascript only reads it), then the solution is to serialize it to json (in the view itself or using a template filter - one might already exists FWIW), bind it to a javascript variable (in the template) and then let the javascript code use it as just any js object, ie (assuming a "jsonify" template filter):
<script>
var data_dict = {% data_dict|jsonify %};
function do_something() {
var key_val = $('#input_id').val();
var data = data_dict[key_val];
// rest of the code
}
// and you'll probably want to bind do_something to
// some js event handler
</script>
There is a similar issue at Get javascript variable's value in Django url template tag
Providing arg1 can be numeric and the reversed url doesn't contain other instances of the string /12345/ then you can use,
var url_mask = "{% url 'someview' arg1=12345 %}".replace(/12345/, tmp.toString());

Can't pass json from html to javascript in Flask? [duplicate]

I want to export a JSON string in python into a JS variable.
<script type="text/javascript">
var data = JSON.parse('{{ dataJSON }}');
console.log(data)
</script>
If I print the content of dataJSON I get: [{"offset":0,"total":1,"units":[{"village_id":37,"village_name":"Glim
But in the JS I get this: JSON.parse('[{"offset":0,"total":1,"units":[{"village_id":37
I use jinja2 template engine: http://jinja.pocoo.org/docs/dev/templates/#if
How can I fix that?
You need to mark the data as safe:
var data = {{ dataJSON|safe }};
This prevents it from being HTML-escaped. There is no need to use JSON.parse() this way; JSON is a valid JavaScript subset (at least insofar that the Python json module produces a valid subset).
Take into account that this doesn't make it JavaScript safe. You may want to adjust your JSON serialisation. If you are using Flask, a tojson filter is provided that ensures you get JavaScript-safe valid JSON:
var data = {{ data|tojson|safe }};
If you are not using Flask, post-process the JSON:
dataJSON = (json.dumps(data)
.replace(u'<', u'\\u003c')
.replace(u'>', u'\\u003e')
.replace(u'&', u'\\u0026')
.replace(u"'", u'\\u0027'))
This is Python code to produce a dataJSON value that can be safely used in HTML (including attribute values) and in JavaScript. Credit here goes to the Flask json.htmlsafe_dumps() function.

ASP.NET generating Javascript object

I need to generate a JSON object from server containing data to be cached on client. I placed the following:
<script src='Path to js file on server" />
At the server, I generated my json data and placed them inside the JS file.
I can see the generated JSON object on the client-side something as:
var jsonData = [{}, {}];
However, when I try to access jsonData object, it says, undefined!
Is there another way to generate valid javascript from server side?
Thanks
This is the server-side code:
var items = List<myObj>();
string json = JsonConvert.SerializeObject(items, Formatting.Indented);
StringBuilder sb = new StringBuilder();
sb.AppendLine();
sb.AppendFormat(" var jsonData = {0};", json);
var fileName = Request.PhysicalApplicationPath + "Scripts/Data.js";
System.IO.File.WriteAllText(fileName, sb.ToString());
As for client side:
<script src='#Url.Content("~/Scripts/Data.js")' type="text/javascript"></script>
I tried to use this code on the client:
alert(jsonData[0].Id);
It says, jsonData is undefined!
Regards
ASP part is ok, the problem seemed to lie in javascript variable scoping plane. Possible problems:
You just don't include that js file.
You're trying to access variable before it is initialized;
Variable isn't visible in place, you're trying to access it.
You're not exact in your question and accessing not jsonData, but something like jsonData[0].property
etc.
UPD: Ok, first two options are excluded. Where are you trying to access this variable? Please, show us a portion of code.

Getting portlet session in JS

Hi I am trying to fetch portlet session in my JS variable. How could I go about it
request.getPortletSession().getAttribute("countryList"); //This is my .java class code
I need to fetch the same in JS?
you can't access to java session via javascript.
One solution is to serialize you java object into json string and save it into session(if object is null, just save a string that equals to "null")
getPortletSession().setAttribute("countryListJson", JSONUtil.toJSON(yourObject));
then you can use
<script type="text/javascript">
var obj = <%=request.getPortletSession().getAttribute("countryListJson")%>;
</script>
Another solution is to provide a json padding controller method for ajax call. and return a string like this :
return "var countryList = " + JsonUtil.toJson(request.getPortletSession().getAttribute("countryList")) +";"
then you should mapping this method to a url such as "/contryList.do"
and in your page:
<script type="text/javascript" src="<%=request.getContextPath()%>/contryList.do"></script>
<script type="text/javascript">
alert(contryList);
</script>
As i understand, you need to place in some JS var the countryList (from controller). You don't need to get portlet session in JS, you should be able to do like follows:
I managed to get some strings from controller to js using scriptlets and usebean. Try something like this:
Let's say i need to alert an error from backend and i have put it in a java string named "error"(in controller).
I'm able to do this(doView):
String error = request.getAttribute("error"); // or it can be simply String error = "sometext"
if ((error != null) || (!error.equals(""))){
request.setAttribute("error", error);
}
else request.setAttribute("error","false");
Then, in your jsp, at the top i'll place an usebean tag like:
<jsp:useBean id="error" class="java.lang.String" scope="request"></jsp:useBean>
Then, between script tags:
var error = "<%=error%>";
if (error != "false") alert(error);
As i noticed, you need to set the var in controller (with setAttribute) using an if / else statement.

Categories