50

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

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?

tvanfosson
  • 524,688
  • 99
  • 697
  • 795

6 Answers6

85

PUT and DELETE are not supported by all browsers, RubyOnRails supports passing an extra parameter with your data called _method which will indicate how RoR will treat the request.

$.ajax({
          type: "POST",
          url: '/admin/pages/1.json',
          data: { _method:'PUT', page : {...} },
          dataType: 'json',
          success: function(msg) {
            alert( "Data Saved: " + msg );
          }
});
Josh K
  • 28,364
  • 20
  • 86
  • 132
duckyflip
  • 16,189
  • 5
  • 33
  • 36
  • 3
    That doesn't seem to be the issue here (and do any modern web browsers really lack support for PUT?). The server /is/ receiving the data, just not parsing it the right way. – Matthew Flaschen May 25 '09 at 20:38
  • 3
    yes most browsers lack PUT and DELETE, only GET and POST. The server could be getting the data on the wrong action, ie. if its a POST it would normally map to the Create action and a PUT would map to the Update action. – Kris Jul 24 '09 at 10:52
  • 5
    http://annevankesteren.nl/2007/10/http-method-support would have me believing otherwise (i.e. that a lot of browsers actually do support PUT and DELETE). – mogsie Jul 16 '10 at 23:05
  • 6
    The `data` is wrong and `dataType` is not what needs to be set. Lost an hour because of this answer. – Marc-André Lafortune May 23 '12 at 03:28
  • 2
    This didn't work for me, the [comment below](http://stackoverflow.com/a/4036113/8137) gave the correct answer: use JSON.stringify on the sent data, and set contentType (not dataType!) to 'application/json'. – JW. Aug 01 '12 at 15:30
  • 1
    @Marc-André Lafortune: so what is the correct answer here or what did not work for you? – Pascal Oct 21 '12 at 13:06
  • 5
    @pascalbetz: The correct answer is lqc's. This answer will *not* make Rails parse this request as json, it will only return json. – Marc-André Lafortune Oct 21 '12 at 21:13
  • 1
    Could you name the browsers lack `PUT/DELETE`? It appears that all of them support it and it's been part of the early HTML 1.1 spec. – Hengjie Mar 04 '13 at 02:34
  • @Kris- you're wrong- all modern browsers support **PUT** and **DELETE** via AJAX, just not with HTML forms. See [lqc's answer](http://stackoverflow.com/a/4036113/165673) on why this isn't working. – Yarin Dec 14 '13 at 22:46
38

The dataType param in jQuery isn't what you send, but rather specifies the format you expect the answer to be (yes, that's a very poor name). If you want to send your data to the server in a format other then application/x-www-form-urlencoded you should use contentType param. You also need to serialize your data:

$.ajax({
      type: "PUT",
      url: '/admin/pages/1.json',
      data: JSON.stringify({...}),
      contentType: 'application/json', // format of request payload
      dataType: 'json', // format of the response
      success: function(msg) {
        alert( "Data Saved: " + msg );
      }
});
E. Zenk
  • 23
  • 4
lqc
  • 7,434
  • 1
  • 25
  • 25
5

Ok, actually my JSON data didn't have the page key, my mistake. So thats why it was not correctly parsing. But now I get "[object Object]" string as the value for page key instead of a nicely parsed json object.

Where should I look: JQuery or Rails?

EDIT:

I've solved my issue stringifying the json object with a script found here: www.json.org/js.html:

$.ajax({
      type: "PUT",
      url: '/admin/pages/1.json',
      data: { page : JSON.stringify( {...} ) },
      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
joshua.paling
  • 13,762
  • 4
  • 45
  • 60
2
var id = $('#route_id').val()
$.ajax({
    type: 'PUT',
    url:  '/routes/'+ id,
    data: $('#markerform').serializeArray(),
    dataType: "JSON",
    success: function(data) {
        console.log(data);
    }
});
1

I had a similar problem [object Object] with jQuery/rails, but with HTML, rather than JSON. Perhaps this will help -

param of [object Object]

data: { lesson: { date: drop_date } }

param of lesson[date]

data: { "lesson[date]": drop_date }

hope this helps -

Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
theschmitzer
  • 12,190
  • 11
  • 41
  • 49
0

You probably just need to set the Request Headers on jQuery.

jQuery.ajaxSetup({ 
  'beforeSend': function(xhr) {
    xhr.setRequestHeader("Accept", "text/javascript");
  }
})
Carlos A. Cabrera
  • 1,920
  • 15
  • 14