Saturday, November 28, 2009

Rails, JSON, & JQuery, Oh My!

So far I've solved 2 of 3 problems (I'm using Rails 2.3.3):

I may not have the error messages verbatim, comment and correct me where that's the case

405 Method not allowed


If you're sending JSON your request.raw_post (in params_parser.rb) ought to look like JSON, in which case you can't use _method => 'PUT' or _method => 'DELETE'. Since you can't rely on the x-www-form-urlencoded values, you have to use a header instead.

// Set the request for any of $.ajax, $.post, $.get, $.getJSON
var method = 'PUT' // or 'DELETE'
$.ajaxSetup({ 
        beforeSend: function(xhr) {xhr.setRequestHeader("X-HTTP-Method-Override", method);},
        scriptCharset: "utf-8",
        contentType: "application/json; charset=utf-8"
      });
$.ajax({
      url: "/questions.json",
      type: "POST",
      data: $.toJSON( {
          question : {
              text : "Life, Universe, & Everything?",
              answer : 42,
              tag : "42"
          }
      },
      dataType: "json",
      success: function(msg){
         alert(msg);
      }
   }
);

INSERT INTO ModelX('val1', 'val2', 'val3') VALUES(NULL,NULL,NULL)


Although the JSON is parsed into Ruby hashes and arrays, it isn't parsed into your model. In the Controller you have to add something like this
if params[:_json]
    params[:question] = params[:_json][:question]
end

:_json is the converted request.raw_post (your POST body).
:question is the name of my model, yours will be different, of course.

Allow method override for GET

Still working on it....

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

Links to this post:

Create a Link

<< Home