Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send simple json response in Rails?

I need to send json response depends on user entered data in input, but I'm failing to send simple json request.

I followed this article - http://paydrotalks.com/posts/45-standard-json-response-for-rails-and-jquery .

Added MimeType:

Mime::Type.register_alias "application/json", :jsonr, %w( text/x-json )   

and in my controller:

 def checkname   respond_to do |format|     format.jsonr do       render :json => {           :status => :ok,           :message => "Success!",          :html => "<b>congrats</b>"       }.to_json      end     end end 

but the screen is empty and here is response code from fiddler2 when I composed GET response to this action:

    HTTP/1.1 406 Not Acceptable    Content-Type: text/html; charset=utf-8    X-UA-Compatible: IE=Edge    Cache-Control: no-cache    X-Request-Id: 14a8467908d9ce322d054607efdacf92    X-Runtime: 0.011000    Content-Length: 1    Connection: keep-alive   Server: thin 1.4.1 codename Chromeo 

What I'm doing wrong ?

like image 958
MID Avatar asked Sep 12 '12 09:09

MID


2 Answers

Not sure about dealing with custom MIME, but as for rendering JSON, this should work:

def testme   respond_to do |format|     msg = { :status => "ok", :message => "Success!", :html => "<b>...</b>" }     format.json  { render :json => msg } # don't do msg.to_json   end end 

Also it might help if you state which version of Ruby and Rails you are using.

like image 122
Lukas Stejskal Avatar answered Sep 28 '22 02:09

Lukas Stejskal


I usually use this method to return json data:

msg = {:token => token, :courseId => courseId} render :json => msg 
like image 24
dalmate Avatar answered Sep 28 '22 01:09

dalmate