Sara Sebbar
Sara Sebbar

Reputation: 3

how to call js function from my controller grails

I'm new in grails, it would be good if someone may help me.

I've a js function that I would call in my controller to open a popup after doing some things in controller.

I've this gsp file:

<g:form controller="admin" method="post">
<table summary="generer PDF">
..
..
<td>
<g:actionSubmit value="generate" action="genererAction"/>
</td>
</tr>
</table>
</g:form>

when the user click at "generate" (button),it must call this function :

def generateAction = {
def result
...
if (result){ 
//here, if result=true a popup will be displayed
}
else  {
redirect(action: 'index')
}}

I wish you can help me. Thank you.

Upvotes: 0

Views: 1946

Answers (1)

Abhishek
Abhishek

Reputation: 462

you can do it with ajax, here is an example :

View :

<g:form controller="admin" method="post">
<table id="tableID" summary="generer PDF">
..
..
<td>
<!--<g:actionSubmit value="generate" action="genererAction"/>-->
<button onclick="preformAction(); return false;">generate</button>
</td>
</tr>
</table>
</g:form>

Controller :

def generateAction = {
def result
...
if (result){ 
//here, if result=true a popup will be displayed
render "success"
}
else  {
//redirect(action: 'index')
render "index"
}}

Script : // copy this script in your view

<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript">
function preformAction(){
    $.ajax({
        url:'${createLink(controller:"admin",action:"generateAction")}', // here you can pass the controller url
        data: {
            // data to be passed to controller
        },
        success : function(response){
            // this block is called after successful processing of controller
            // here you can call your js function after controller has finished its processing
            // consider response has 'success'
            if(response == 'success'){
                 OpenSAGPopup();
            } else if(response == 'index'){
                 window.location = '${createLink(controller:"admin",action:"index")}';
            }

        },
        error : function(response){
            // this block executes if any error occurs with the processing of controller
            alert("Error while generating pdf");
        },
    });
}
</script>

try this, if it work let me know....

Happy Coding.

Upvotes: 1

Related Questions