How do I PUT JSON data to Ruby on Rails using jQuery?

16,110

Solution 1

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.

Solution 2

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

$.parseJSON("some_jsonish_string")

Solution 3

You need to set contentType to "application/json" in your options; dataType is only what you expect back.

Also, you need to serialize your data field using JSON.stringify:

$.ajax({
    type: "PUT",
    url: '/admin/pages/1.json',
    data: JSON.stringify({ page :  {...} }),
    contentType: 'application/json',
    dataType: 'json',
    success: function(msg) {
        alert( "Data Saved: " + msg );
    }
})
Share:
16,110
Admin
Author by

Admin

Updated on June 20, 2022

Comments

  • Admin
    Admin almost 2 years

    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 );
          }
    });
    

    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:inparse' (DELEGATION):2:in __send__' (__DELEGATION__):2:inparse' /Library/Ruby/Gems/1.8/gems/activesupport-2.3.2/lib/active_support/core_ext/hash/conversions.rb:154:in `from_xml' ... ...

    It is like Ruby on Rails is trying to parse the parameters as XML, but I want to use JSON!

    What shall I do to put JSON to Ruby on Rails?