Eli Davila
Eli Davila

Reputation: 577

How do you pass a JavaScript variable to your Groovy controller?

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?

Upvotes: 1

Views: 6667

Answers (2)

MKB
MKB

Reputation: 7619

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>

Upvotes: 2

James Kleeh
James Kleeh

Reputation: 12228

Look at the documentaton.

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

Upvotes: 0

Related Questions