4

Here is my code for making POST request:

function post(path, params, method) {
  method = method || "post"; // Set method to post by default if not specified.

  // The rest of this code assumes you are not using a library.
  // It can be made less wordy if you use one.
  var form = document.createElement("form");
  form.setAttribute("method", method);
  form.setAttribute("action", path);
  form.setAttribute("enctype", "application/json");
  for(var key in params) {
    if(params.hasOwnProperty(key)) {
      var hiddenField = document.createElement("input");
      hiddenField.setAttribute("type", "hidden");
      hiddenField.setAttribute("name", key);
      hiddenField.setAttribute("value", params[key]);

      form.appendChild(hiddenField);
    }
  }

  document.body.appendChild(form);
  form.submit();
}

I tried to set the Content-type in HTTP header to "application/json" by setting enctype of the form to "application/json". However, it doesn't work.

I saw an unofficial draft about supporting "application/json" for enctype however it seems not accepted yet..

Does anyone have ideas about how to make a POST request and use JSON instead of formdata as the data format without resorting to AJAX?

Community
  • 1
  • 1
Hanfei Sun
  • 45,281
  • 39
  • 129
  • 237
  • 4
    It looks like the actual values from the DOM that is used for the HTTP header is the `HTMLFormElement.encoding` object property, which will revert to one of the three allowed values even if directly changed, per the HTML 5 spec : http://www.w3.org/TR/html5/forms.html#dom-fs-encoding – Anthony Aug 11 '15 at 07:03
  • 2
    So it's not a matter of "can it be done" so much as "even if you try, will the browser ignore your attempts", which it does, it seems. – Anthony Aug 11 '15 at 07:03

1 Answers1

3

Does anyone have ideas about how to make a POST request and use JSON instead of formdata as the data format without resorting to AJAX?

There is no way to do this. Work on JSON as a form encoding type has been abandoned.

If you are writing an HTTP endpoint that expects normal form submissions, write it so it accepts application/x-www-form-urlencoded and multipart/form-data encoded data.

Those are the only encoding types that browsers support for form submissions (other than text/plain which isn't suitable for machine processing).

The only way to send a JSON payload is with Ajax, which you rejected as an option.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Quentin, I wonder that, If we cant change data type by enctype, Why they needed it? I confused. I faced same problem and I did not solve it too. Is not there any way to post data as application/json? – Kamuran Sönecek Aug 11 '15 at 06:57
  • 2
    You can change the encoding of the data using `enctype`. You just can't change it to encodings that the browser doesn't know about. – Quentin Aug 11 '15 at 07:36