views:

2717

answers:

4

Hi, I am trying to send a jquery ajax PUT request that looks like this:

$.ajax({
      type: "PUT",
      url: '/admin/pages/1.json',
      data: { page : {...} },
      dataType: 'json',
      success: function(msg) {
        alert( "Data Saved: " + msg );
      }

});

and my controller looks roughly like this:

      respond_to do |format|
         if @page.update_attributes params[:page]
           format.html{ ... }
           format.json{ render :json => {:saved => 'ok'}.to_json }
         else
           format.html{ ... }
           format.json{ render :json => {:saved => 'fail'}.to_json }
         end
       end

but I get the following error:

The error occurred while evaluating nil.name /Library/Ruby/Gems/1.8/gems/activesupport-2.3.2/lib/active_support/xml_mini/rexml.rb:29:in merge_element!' /Library/Ruby/Gems/1.8/gems/activesupport-2.3.2/lib/active_support/xml_mini/rexml.rb:18:in parse' (DELEGATION):2:in __send__' (__DELEGATION__):2:in parse' /Library/Ruby/Gems/1.8/gems/activesupport-2.3.2/lib/active_support/core_ext/hash/conversions.rb:154:in `from_xml' ... ...

Is like Rails is trying to parse the params as XML, but I want to use JSON!!

What shall I do to put JSON to rails?

+2  A: 

You need to set contentType in your options. contentType is what you are sending. dataType is what you expect back. You should carefully read the documentation on the options argument to ajax.

Craig Stuntz
A: 

Also, head's up, but there's a bug in Rails 2.3.2 that prevents this from working:

https://rails.lighthouseapp.com/projects/8994/tickets/2448-rails-23-json-put-request-routing-is-broken

A: 

Setting the contentType didn't work for me I was getting a string instead of a hash for params[:page]

So I solved like this:

Strigifying the json object with a script found here: www.json.org/js.html:

 $.ajax({
  type: "PUT",
  url: '/admin/pages/1.json',
  data: { page : JSON.strigify( {...} ) },
  dataType: 'json',
  success: function(msg) {
    alert( "Data Saved: " + msg );
  }
});

On the rails side json gem must be required. In the controller:

 params[:page] = JSON.parse params[:page] if params[:page].is_a? String

is not pretty at all but worked for me.

Sorry I possed the question twice...

Be careful with this - PUT isn't supported by all browsers. Some only do GET and POST, I'm not sure which.
skaffman
A: 

If you don't want to add scripts, you could do

$.parseJSON("some_jsonish_string")
Stefano