0

I am having trouble accessing params in Sinatra after submitting a form. This is my form:

function submitForm(e) {
    e.preventDefault();

    $.ajax({
      type: 'POST',
      url: '/mix_addresses',
      //grab the inputs from address_section
      //data: $('.add_address_section .add_address_field').map(function() { return $(this).val() }),
      data: [1,2,3],
      dataType: "json",
      success: function(data) {
        debugger;
      }
    });
  }

And this is my endpoint:

require 'sinatra'
require 'jobcoin_client'

get '/' do
  erb :add_coins
end

post '/mix_addresses' do
  puts params
end

I'm getting to the endpoint, but the params are blank. Shouldn't it be [1,2,3]? Instead, it's:

{"undefined"=>""}

Anyone see what I'm doing wrong?

Jwan622
  • 11,015
  • 21
  • 88
  • 181

1 Answers1

1

Several issues here :)

Sinatra configuration

Main problem is coming from the fact that Sinatra doesn't deal with JSON payloads by default. If you want to send a JSON payload, then the easiest solution will be :

  1. To add rack-contrib to your Gemfile,
  2. Then, require it in your sinatra app: require rack/contrib
  3. And load the middleware that deals with this issue: use Rack::PostBodyContentTypeParser

And you should be good to go!

Source: several SO post reference this issue, here, here or here for instance.

jQuery ajax call

Also, note that there might be some issues with your request :

  1. You'll need to use a key: value format for your JSON payload: { values: [1,2,3] }
  2. You'll need to stringify your JSON payload before sending it: data: JSON.stringify( ... )
  3. You'll need to set the request content type to application/json (dataType is related to the data returned by the server, and doesn't say anything about your request format, see jQuery ajax documentation for more details).

Eventually, you should end up with something like this on the client side:

function submitForm(e) {
  e.preventDefault();

  $.ajax({
    type: 'POST',
    url: '/mix_addresses',
    contentType: 'application/json',
    dataType: 'json',
    data: JSON.stringify({ values: [1,2,3] }),
    success: function(data) {
      debugger;
    }
  });
}
Pierre-Adrien
  • 2,836
  • 29
  • 30