View Full Version : How to generate a response message using Rails?

3 Dec 2009, 6:41 AM
I've defined a simple handler to display the response message on the page.
(I've used the "App.js" under "/ext/examples/shared/extjs", and the "App" object has been created.)

function writeHandler(store, action, result, resp, rs) {
App.setAlert(resp.success, resp.message);
var store = new Ext.data.JsonStore({
root: 'users',
totalProperty: 'totalCount',
idProperty: 'id',
remoteSort: true,
restful: true,
writer: writer,
baseParams: { format: 'json' },
fields: ['username'],
proxy: new Ext.data.HttpProxy({ url: '/users' }),
listeners: {write: writeHandler}
Then I code the UsersController to generate a response code like this:

render :json => { 'success' => true, 'message' => 'User has been deleted!' }
In the Firebug, I can see the content of the "Response" tab is:

{ "success": true, "message": "User has been deleted!" }
But the message cannot display in the page. Does the way I use to generate the response message is incorrect? By the way, the "content-type" of the response is "application/json". Is it the rub?

3 Dec 2009, 10:14 AM
I am assuming that you resp is the response object.

This means that you get a response, but the text is in responseText. Now you want to decode it first to make an object, and then call it.

var obj = Ext.decode(response.responseText);
App.setAlert(obj.success, obj.message);

3 Dec 2009, 7:49 PM
Thanks! But this code still doesn't work. I set a breakpoint using Firebug in "writeHandler" function to inspect the variable "resp" - which, according to the EXTJS API document, is the response object of a broswer. I got the following result:

action "destroy"
data undefined
message undefined

- raw Object message=Delete OK! success=true
message "Delete OK!"
success true

records undefined
success true

It seems that the message I send by server cannot be decoded correctly. Maybe my approach is not correct using "render :json =>..." in rails. But what's the right way to do so?

3 Dec 2009, 8:21 PM
It doesn't work meaning, you don't get those objects.

What is responseText? What is obj.success? What is obj.message?

3 Dec 2009, 8:53 PM
"resp.responseText" is undefined. So the code

var obj = Ext.decode(resp.responseText);

Returns a undefined object (that means the "obj" is undefined).

However, after checking the response object in Firebug, I try to display the raw message of the response:


I can get the message the server returns. So I guess my server-side code below:

render :json => { 'success' => true, 'message' => 'User has been deleted!' }

It's not a right way to generate the response object.

3 Dec 2009, 11:47 PM
If your'e using FireBug already then check the request/responses in the Net Tab (XHR) to see if your handler is posting correct JSON data (BTW, I'm using 'application/x-json' as the content/type).