rails / jquery-ujs

Ruby on Rails unobtrusive scripting adapter for jQuery
MIT License
2.61k stars 508 forks source link

Why does my form always get submitted with Content-Type:application/x-www-form-urlencoded; #506

Open JohnSmall opened 6 years ago

JohnSmall commented 6 years ago

I'm trying to send a form with Content-Type:application/json; I set

`<form data-remote="true" data-type="json">...</form>`

As it says in the documentation.

But it's always sent as Content-Type:application/x-www-form-urlencoded;

Is this a bug or is there a special undocumented gotcha such that setting data-type='json' doesn't actually send json encoded data.

jeremy commented 6 years ago

What are you seeing when you step through in the debugger?

l4cr0ss commented 5 years ago

I have the same problem. With data-remote: true my form is still being submitted as 'Content-Type': 'application/x-www-form-urlencoded'.

See this example repl.it that illustrates the problem. Try and submit the form without any input and notice that www-form-urlencoded is submitted and HTML is returned, even though form has data-remote: true set.

https://repl.it/repls/TriangularEmptyWireframes

l4cr0ss commented 5 years ago

It looks like this could be related to https://github.com/rails/rails/issues/20610. Adding a format.js to the respond block fixes the return type issue (it returns JSON instead of HTML). However, the rails-ujs parser still breaks because it's expecting HTML.

l4cr0ss commented 5 years ago

Setting data type to json fixes the issue, like form_with(..., data: { type: 'json' }) do |form|..

Doing this means you don't have to create a format.js response