Is it possible to execute a Grails dynamic finder query from JavaScript block

41 Views Asked by At

I am using Grails 2.5.2. I am trying to execute a dynamic finder query from JavaScript block with a variable. But the JS variable is not recognized. How can I do this?

My attempts as below:

$(".usrname").blur(function() {
        var username = $(this).val();
        var fullName = "${User.findByUsername(username)?.fullName}";
        alert(fullName);
    });
1

There are 1 best solutions below

1
iroli On

it won't work because it's rendered into html before your variable username value is known.

you have to use an action in your controller

def findUser() {
    def fullName = User.findByUsername(params.username)?.fullName
    return fullName
}

and then use ajax function in your gsp

$('.usrname').blur(function(){

    var username = $(this).val();
    var URL ="/yourController/findUser/?username=" + username;                                                                          

    $.ajax({
        url:URL,
        success: function(resp){
            alert(resp);
        }
    });
});