Grails + JQuery

Today I had a bit of time to do some further grails fooling around. I already had a working application old school (so everything you do was a page refresh.). I wanted to do some small Ajax stuff (getting a product using it’s id and then prefilling the price fields with that value.)

In my domain I have the following object

class Product {

String name
String description
double buyInPrice
double unitPrice
double vatPerc

static hasMany = ['productPricings':ProductPricingHistory]

String toString(){
return "${description} ${unitPrice}"
}
}

In my controller I have to following

import grails.converters.JSON

class ProductController {

def scaffold = Product

def showjson = {
def product = Product.get(params.id)
render product as JSON
}

}

In my gsp I have to following snippit

$(document).ready(function(){
$("#product\\.id").change( function() {
setPrice($(this).val());
});
$("#units").change(function(){
calculatePrice();
});
});
function setPrice(productId){
$.ajax({
url:"../product/showjson/"+productId,
dataType:"json",
success:function(json){initProduct(json);},
error:function(xhr){
alert("Failed to save patient!: " +
xhr.status + ", " + xhr.statusText );
}

});
}

function calculatePrice(){
var unitprice = $("#unitprice").val();
var units = $("#units").val();
$("#priceExcl").val((unitprice * units));
}

function initProduct(json){
$("#unitprice").val(json.unitPrice);
}

As you can see it is really nice. Okay with Java + DWR this is also very simple, but here I have it in my controller and just say render … as JSON and grails does the rest. Actually I still have to look if Spring has some kinde of build in JSON renderer. Probably somebody already created this. But hey now I save and run (no need for start stop of my application server 😀 ) and in the end it’s still bytecode I’m using.

I still have to do some grails testing where I generate my backend in JPA and include it in a jar. However the grails/groovy part should still be reloadable, right? Anybody tried this yet?

Leave a Reply