Ajax call is not going through the withFormat->json on GRAILS controller

grails, jquery

Solution

This is usually something that gets people, especially when moving from Grails 1.x to Grails 2.x. You have to read the docco carefully.

emphasis in bold is mine...

Another important factor to note is that the withFormat method deals with the response format and not the request format. As of Grails 2.0, there is a separate withFormat method made available on the request that you can use to handle the request format which is dictated by the CONTENT_TYPE header of the request:

request.withFormat {
    xml { .. }
    html { .. }
}

Problem

I have a gsp page that includes a JS function ( named "sample") which does an ajax call. ``` function sample() { var params = { office: {id: "testId"}, population: {id: "testId2"}}; $.ajax({ url: "http://localhost:8080/officeProj/mustache/list", cache: false, contentType: "application/json; charset=utf-8", type: "POST", dataType: "json", data: JSON.stringify(params), complete:function(json){ console.log(" reponse :"+ json); }, success: function(officeData) { var template = "<h1>{{data.firstName}} {{data.lastName}}</h1>"; var html = Mustache.to_html(template, data); $('#sampleArea').html(html); } , error: function (XMLHttpRequest, textStatus, errorThrown) { console.log("error :"+XMLHttpRequest.responseText); } }) } ``` Now, this ajax call reaches the appropriate GRAILS controller and appropriate action,defined as: ``` def list = { withFormat { html { return [title: "Mustache" , data:[firstName:"Indiana", lastName:"Jones"], address:"NYC" ] } json { // extract the data to be rendered to the page println("processing JSON.....") render ([title: "Mustache" , data:[firstName:"Indiana", lastName:"Jones"], address:"NYC" ] as JSON) } } } ``` The problem is that the control NEVER goes through the withFormat->json in the controller-action and hence I am not seeing the expected result.( When the control comes back to the gsp page, it goes through the the "complete" but not through the "success". No error recorded. Can any one see any problem with my ajax call? Please let me know if I need to provide more information.Thanks in advance.

Original source