How do I PUT data to Rails using JQuery

JqueryRuby on-RailsAjaxJson

Jquery Problem Overview


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?

Jquery Solutions


Solution 1 - Jquery

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

Solution 2 - Jquery

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

Solution 3 - Jquery

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

Solution 4 - Jquery

var id = $('#route_id').val()
$.ajax({
    type: 'PUT',
    url:  '/routes/'+ id,
    data: $('#markerform').serializeArray(),
    dataType: "JSON",
    success: function(data) {
        console.log(data);
    }
});

Solution 5 - Jquery

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 -

Solution 6 - Jquery

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

jQuery.ajaxSetup({ 
  'beforeSend': function(xhr) {
    xhr.setRequestHeader("Accept", "text/javascript");
  }
})

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMacario OrtegaView Question on Stackoverflow
Solution 1 - JqueryduckyflipView Answer on Stackoverflow
Solution 2 - JquerylqcView Answer on Stackoverflow
Solution 3 - JqueryMacario OrtegaView Answer on Stackoverflow
Solution 4 - Jquerydsn raghavendra raoView Answer on Stackoverflow
Solution 5 - JquerytheschmitzerView Answer on Stackoverflow
Solution 6 - JqueryCarlos A. CabreraView Answer on Stackoverflow