Prakash
Prakash

Reputation: 388

Passing gstring to javascript function in Grails

I am passing a gstring as a parameter to a javascript function as shown:

<div class="btn btn-small" id="helpful" onClick="helpful(${value})">Helpful</div>

Here, value comes from controller which is dynamic. I have javascript function as:

function helpful(answer){
        $.post("${createLink(controller: "reviews", action: "dataFromReviews")}",
                {
                    helpful:true,
                    answer:answer
                }
        );
    }

But I am not getting any response. No error while inspecting. Can't we pass gstring in javascript? Please help.

Upvotes: 0

Views: 66

Answers (2)

jmallen
jmallen

Reputation: 71

As @helgew suggests, check the output. Also note that grails >2.3 will HTML encode anything passed in with a GString unless you have disabled this (grails.views.default.code='none'). You'll need to use the raw codec to avoid the encoding. Use with caution:

<div class="btn btn-small" id="helpful" onClick="helpful('${raw(value)}')">Helpful</div>

Upvotes: 1

helgew
helgew

Reputation: 361

What does the generated HTML look like? I would think that you have a javascript error in it because you are not quoting the extrapolated string you are using as a parameter for the 'helpful' function. This should work:

<div class="btn btn-small" id="helpful" onClick="helpful('${value}')">Helpful</div>

Upvotes: 0

Related Questions