There are three data format we can post through AJAX (from JavaScript): serialization, and xml. Serialization is the process that formats a set of data so that the server can easily read
it from javascript object or html form.
// Serialized form
name=Chhorn&last=Chamnap&city=Cambridge&zip=02140
//XML
<name>Chhorn</name>
<last>Chamnap</last>
<city>Cambridge</city>
<zip>02140</zip>
Rails automatically recognizes these format very well. In your controller, you can access from params[:name], params[:last],.... However, you would face difficulties when you do a post request with json object. In your params variable would be {"{\"first_name\":\"chamnap
\",\"last_name\":\"chhorn\"}"=>nil. Therefore, you must parse this string to ruby object. There are two possible solutions. First solution, I got from a discussion.
irb> require 'rubygems'
=> true
irb> gem 'json'
=> true
irb> require 'json'
=> true
irb> raw = "{\"first_name\":\"chamnap\",\"last_name\":\"chhorn\"}"
=> "{\"first_name\":\"chamnap\",\"last_name\":\"chhorn\"}"
irb> puts raw
{"first_name":"chamnap","last_name":"chhorn"}
=> nil
irb> JSON(raw)
=> {"first_name"=>"chamnap", "last_name"=>"chhorn"}
irb> cooked = JSON.parse(raw)
=> {"first_name"=>"chamnap", "last_name"=>"chhorn"}
irb> raw
=> "{\"first_name\":\"chamnap\",\"last_name\":\"chhorn\"}"
irb> cooked
=> {"first_name"=>"chamnap", "last_name"=>"chhorn"}
irb> raw.class
=> String
irb> cooked.class
=> Hash
irb> cooked["first_name"]
=> "chamnap"
irb> cooked[:first_name]
=> nil
Secondly, I found by chance from my book by using
ActiveSupport::JSON.decode()
method.
2 comments:
Hi Friend,
Nice to see your Blog.....I Like you Blog.
I am also interested in latest news, sometimes i posted on my blog.....
Thanks.
Post a Comment