Question

I have a JSON object that I want to post to a remote server (Rails). All attempts to send it to the server as 'application/json' fail where POST parameters are converted somewhere to url-encoded string. For example:

appAPI.request.post({
  url: "http://mybackend",
  postData: {hello: 'world', foo: 'bar'},
  onSuccess: function(response) {
    console.log("postback succeeded with response: " + response)
  },
  onFailure: function(httpCode) {
    console.log("postback failure: " + httpCode)
  },
  contentType: 'application/json'
});

Returns HTTP 500 with the server complaining from a malformed JSON object:

Error occurred while parsing request parameters.
Contents:

MultiJson::LoadError (784: unexpected token at 'hello=world&foo=bar'): 
  /Users/hammady/.rvm/rubies/ruby-1.9.3-p448/lib/ruby/1.9.1/json/common.rb:148:in `parse'
  ...

What else should I do to send the JSON object to my Rails backend?

Was it helpful?

Solution

You need to stringify the object first.

postData: JSON.stringify({hello: 'world', foo: 'bar'});

OTHER TIPS

use JSON.stringify to stringify the posted data

appAPI.request.post({
  url: "http://mybackend",
  postData: JSON.stringify({hello: 'world', foo: 'bar'}),
  onSuccess: function(response) {
    console.log("postback succeeded with response: " + response)
  },
  onFailure: function(httpCode) {
    console.log("postback failure: " + httpCode)
  },
  contentType: 'application/json'
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top