1

I have been searching on Google for a really good while, and I cannot find a solution to this problem. I am trying to access a JavaScript variable from my GSP file in my Groovy controller, but I can't find out how to do this.

Example:

//JavaScript stuff
<script>
    function validateForm(){
         var ret = false
    }
</script>

//Groovy controller stuff
def myAction = {
    println params.ret
}

How do I achieve something similar to this?

3
  • Have you tried anything yet (with session at least)? Commented Aug 7, 2013 at 1:53
  • I have tried remoteFunction but I get a java script error so it might work but I dont know the syntax of it. This is how I have it in my javascript ${remoteFunction(controller: ActionsController, action:'ImplementNewPixel', params: 'ret')} But no I have not tried anything with sessions yet. How would you use sessions? Commented Aug 7, 2013 at 1:56
  • You should be able to pass the variable using remoteFunction. Have a look at the way params are passed in remoteFunction. Commented Aug 7, 2013 at 2:45

2 Answers 2

2

Two ways to pass a variable to the controller:

  1. Ajax
  2. Form submit

Ajax

  • Use remoteFunction

    ${remoteFunction(controller: 'actionsController' , action: 'implementNewPixel', params: '\'ret=\' + ret')} 
    
  • Use Ajax

    var ret = false;
    jQuery.ajax({
        url: "${createLink(controller: 'actionsController', action: 'implementNewPixel')}",
        data: "ret=" + ret,
        success: function (data) {
            alert(data);
        }
    });
    

etc.

Form submit

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
    var ret;
    function validateForm(){
        ret = false;
    }

    jQuery(function () {
        jQuery("[name='jftForm']").submit(function () {
            jQuery("[name='ret']").val(ret);
        });
    });
</script>

<g:form name="jftForm" controller="actionsController" action="implementNewPixel">
    ...
    <g:hiddenField name="ret" value=""/>
    <g:submitButton name="submit" value="Submit"/>
</g:form>
Sign up to request clarification or add additional context in comments.

2 Comments

I have tried both of your methods but I still cannot access the variable in my controller. Would I be able to access it by using params.ret in my controller? Also when I try using the Form submit method, I get a java script error like so Uncaught ReferenceError: $ is not defined ImplementNewPixel:133 (anonymous function)
Include jQuery in your page.
0

Look at the documentaton.

params: '\'ret=\' + ret'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.