Search code examples
grails

Grails : Call JS from Controller


I have a controller with a method in it:

class teachController {

   def updateIndex () {

    // Do something here
    ----------
  }
}

Now in the GSP there's a JavaScript function:

var drawIndex (var indexValues) {

  // Do something here
 -----------------
  }

How can i call the above JavaScript function from inside the controller function?


Solution

  • If what you want to do is to update a table with data dynamically from the controller. I would use ajax to execute the javascript function "drawIndex()" after it calls the controller action "updateIndex()".

    class teachController {
        def updateIndex(){
             // Do something here
              withFormat {
                    json {  
                        render indexValues as JSON
                    }
              }
        }
    }
    

    Then from your gsp you call the controller action by the name updateIndex.json and using remoteFunction

    function dynamicallyUpdateTable(){
        ${remoteFunction(
               action: 'updateIndex.json',
               onSuccess: 'drawIndex(data)' 
                        )
       }
    }
    

    This will call your javascript function

     function drawIndex(indexValues){
            // Do something here
            //console.log(indexValues)
        }
    

    And that should work. (at least in the way I like to do it) Hope it helps.