6

I have a question using grails variable values in javascript code in a GSP file.

For Example: I have a session value session.getAttribute("selectedValue") and I want to use this value inside javascript code part.

My solution is now (inside a GSP):

<%
    def js = new String("<script type=\"text/javascript\">")
    js += "var jsSelectedValue = " + session.getAttribute("selectedValue") + ";"
    js += "</script>"
    out << js
%>

and then I have javascript block inside my GSP with jQuery Stuff and so on, there I need this value.

Is there another way to have grails variables accessible inside pure javascript code?

And second question, the exactly other way around. I select for example in a dropdown box and click "save" and then i want to store the value $("#select-box").val() inside a session variable from JS-part.

Thank you very much in advance for your help.

Cheers,

Marco

grailsInvas0r
  • 655
  • 2
  • 10
  • 25
  • You're not really referencing any grails variables in the code above. What you're actually doing is using generating javascript code from a template. This template can access the session because it is processed on the server side. – Dónal Aug 09 '11 at 14:45

2 Answers2

12

Why do not use the javascript GSP-tag? A solution can look like this:

<g:javascript>
    var jsSelectedValue = "${session.selectedValue}"; 
</g:javascript>
Alexander Suraphel
  • 10,103
  • 10
  • 55
  • 90
Medrod
  • 986
  • 7
  • 17
  • 2
    Not sure if anyone else will get stuck in the same way I did, but make sure that the var declaration is in a separate tag than any script with a source parameter. – RasTheDestroyer Aug 23 '12 at 21:42
1

The solution to your first problem might be as follows:

UPDATE: Modifications according to @Medrod's solution:

<script type="text/javascript">
var jsSelectedValue = "${session.selectedValue}";
</script>

And for second question:
Send selected value to server and set session variable.

mj.scintilla
  • 638
  • 1
  • 9
  • 20
  • Thanks Medrod and Zedwal! For the answer of the second question, if I send everything to the server (e.g. JSON POST) every script kiddie can prepare some local form values and prepared ajax post and manipulte... right?! – grailsInvas0r Aug 09 '11 at 19:47