Eli Davila
Eli Davila

Reputation: 577

How do you pass a variable from grail's Controller to gsp file via Ajax?

I am trying to display an alert message saying congratulations after the user inputed some data. The thing is that I validate the input in my controller. If there is an error, I pass the appropriate variables to my view to hightlight the fields that are incorrect I do not know how to display the congratulations alert box though. This is what I have tried but it does not work. Any help? Thanks!

//In my ImplementNewPixel.gsp
<script>
         $.ajax({
                success:function(result){
                    if(result.message != null && result.message != ""){
                        alert(result.message);
                    }
                }
            });      
</script>

//In my actionsController:
def validate = {

    String message = ""

    if(Info is not valid){
       //return appropriate info to highlight incorrect textfields
    }

    else{
       message = "Congratulations your tracking pixel has been created and added!" as JSON
    }

    return [message: message, OtherStuff: OtherStuffThatIPassToMyGSP]
}

This not my exact code. I only included the main things that involve this problem.

Upvotes: 0

Views: 1405

Answers (2)

Philippe
Philippe

Reputation: 6828

Just return your message variable in the model of your controller action (see http://grails.org/doc/latest/guide/theWebLayer.html#modelsAndViews), like :

return [message : message]

...and use ${message} in your gsp to retrieve its value, like this :

alert("${message}")

Upvotes: 1

codelark
codelark

Reputation: 12334

Since you're using ajax, you need to return the model in something your javascript library understands. You appear to be using jQuery which will automatically determine the data type by the response's content-type.

class MyController {
    def validate() {
        return [message: "hello there"] as JSON
    }
}

Upvotes: 0

Related Questions