I'm using Sinatra. I've got a button that sends a JSON-formatted string to the server by making a POST request. Only problem is, the JSON string isn't getting to the server.
Here's index.erb
:
<input id="post-button" type="button" value="Send POST request">
Here's script.js
:
window.onload = function(){
var btn = document.getElementById('post-button');
btn.onclick = function(){
var req = new XMLHttpRequest();
var reqObj = {
name: 'Joe',
age: '100'
};
var reqJSON = JSON.stringify(reqObj);
req.open('POST','/post_target',true);
req.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
req.send(reqJSON);
}
}
And finally, main.rb
:
get '/' do
erb :index
end
post '/post_target' do
p params
end
When I click the button and check Firebug, I see that the browser sent a POST request. But when I check the Ruby console, it prints {}
for params
. If it worked right, I guess params
would show a JSON object in string form, along with whatever else it would show.
I'm running Sinatra on my machine, at address http://localhost:4567
.
What am I doing wrong? If I need to do the request with jQuery, I can do that, but can it be done with "vanilla" JavaScript?