Search code examples
jqueryhttpformshttp-post

Set "enctype" attribute to "application/json"


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?


Solution

  • 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.